Create and Open Microsoft Word Document from/through .NET / Asp.Net

Couple of days ago, I encountered with one requirement for Asp.net page, to create New Document and Open Document which is already present on disk at predefined location.

After many clicks on Google and Live , I got proper solution.

Here I putting this in simple steps.

1) We will need to add reference for Microsoft Word Object Library for that you need to go to Solution Explorer =>Add Reference => Select COM Tab

=> Then select “Microsoft Word 11.0 Object Library”

(There can be version change, in my case it is Office 2003 Professional.)

2) Add “using Microsoft.Office.Interop;” in the namespace listings of code file / .cs file where we are going to write code for create or open document using C#.

3) One simple code snippet / function to create blank word document, just simply put this function on button click event or where you want.

CreateNewDocument ()

{

// create reference for Word Application.
private Word.ApplicationClass newWordApplication = new word.ApplicationClass();

object missing = System.Reflection.Missing.Value;

// create reference for document.
private Word.Document newWordDocument = newWordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);

newWordDocument.Activate();

}

4) Code snippet to Open word document which already present at certain location.


OpenWordDocument ()
{

// create reference for Word Application.
private Word.ApplicationClass newWordApplication = new word.ApplicationClass();

object missing = System.Reflection.Missing.Value;
object fileName = strFileName; // name of file with path.
object readOnly = false;
object isVisible = true;



// create reference for document.
private Word.Document newWordDocument
= newWordApplication.Documents.Open
(ref fileName, ref missing, ref readOnly,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing);

newWordDocument.Activate();

}

Advertisements

One thought on “Create and Open Microsoft Word Document from/through .NET / Asp.Net”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s