Automating Microsoft Word 2007 with C Sharp

Hi,

Some time in our project we need to work with word (winword) document programmatically. Word provides a good way to automate nearly all the functionality that can be used through interface.  The process of programmatically working with word document is commonly termed as word Automation.

I will be using a series of blogs to discuss some of the functionality that can be achieved through word automation. In this Blog I will discuss how we can start programmatically open a new or and existing word document and close it.

To work with word 2007 automation we need to have the word 2007 installed in the machine where the application will run. When we install the word 2007, it also installs with it the com component required to automate word 2007.

To start working on the word automation we first need to reference the dll in the project. For this you need to click on the add reference in the project and go to the Com tab. There find the com component called Microsoft Office 12.0 Object Library. The namespace used for the word automation is Microsoft.Office.Interop.Word.

To create or open an existing word document we first need to open the word application. Then open or create the word document and last but not the least close the document.

Here is a code on how to do it. Remember to work with word programmatically; word takes a lot of parameter which might not be required in normal working. In most of the cases we will pass missing value to these parameters. Also all the value passed to word document needs to be passed as reference and not as value. Here is a code snippet of how to open a new word document.

//Create an object for missing values. This will be passed when ever we don’t want to pass value

Object missing = System.Reflection.Missing.Value();

//Objects for true and false to be used in the word document for passing true or false.

Object true = true;

Object false = false;

 

        

//Creating objects of word and document

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

       

//Adding a new document to the application

oWordDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing);

 

// To open an existing word document we need to pass the path of the existing document with some // other parameters. Here is the code snippet opening an existing word document

 

object fileName = “Path_of_the_file_to_Open”;

// You can keep it true if you want to open the file in readonly mode

object readOnly = false;

// we can keep it false if you want to open the file but not make it invisible

object isVisible = true;

oWordDoc = oWord.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, ref missing);

 

To close the word document properly. We first need to close the word document and then the word application. If we do not close the word application then the memory will never be released for the word application.

//Closing the file

oWordDoc.Close(ref oFalse, ref missing, ref missing);

 

//Quitting the word application to release the memory.

oWord.Quit(ref missing, ref missing, ref missing);

Vikram

Published Tuesday, July 01, 2008 9:15 AM by vik20000in

Comments

# re: Automating Microsoft Word 2007 with C Sharp

Tuesday, July 01, 2008 5:12 AM by hao.peng

so easy... hopefully don't need to experience the pain in VB

# Programmatically replace word with the help of Word Automation

Friday, July 04, 2008 5:20 AM by Vikram Lakhotia

Hi, In My last two posts I talked about · How to open and close a word document programmatically . ·

# rascunho » Blog Archive » links for 2008-07-04

Friday, July 04, 2008 4:37 PM by rascunho » Blog Archive » links for 2008-07-04

Pingback from  rascunho  » Blog Archive   » links for 2008-07-04

# re: Automating Microsoft Word 2007 with C Sharp

Monday, July 07, 2008 12:52 PM by infomaven

Has anyone tried to access Word doc tables using this dll? I would like to retrieve values entered to a specific column in a Word doc table. I'd appreciate your thoughts and insights.

# re: Automating Microsoft Word 2007 with C Sharp

Tuesday, July 29, 2008 6:58 AM by nikhil jain

hi

I am try to automate the world through Asp.net3.5 VS2008 version

But after adding The com Refrence When i am Trying to use Microsoft.Office.Interop.Word then after office only one option is there i.e. core

nothing other then that

can you help me please

my email address is nj.nikhiljain@gmail.com

# re: Automating Microsoft Word 2007 with C Sharp

Thursday, August 07, 2008 2:39 PM by amit174

Hi,

I am trying open a document for user to make changes and then I want to save it as different name. (in asp.net 2.0)

1) for document.open() call I have visible parameter set to true but I am not able to see that document.  if I put oWord.visible = ture right after above open() call, it opens up 2 documents one blank one and one that I am trying to open.

2) when user clicks on button I want to perform save as and than close() and quit(). Here save as works but close and quit does not work.

I'll appreciate your help.

Amit

# re: Automating Microsoft Word 2007 with C Sharp

Tuesday, August 26, 2008 11:50 PM by Wael

It's working perfect with me on win 2003(IIS6). After publishing it to our new Win2008(IIS7) It gave me the following error:

System.UnauthorizedAccessException was unhandled by user code

 Message="Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005."

 Source="App_Web_o3gwip7c"

This error occurs on the following line of code:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

Does anyone tried this on IIS7?

# re: Automating Microsoft Word 2007 with C Sharp

Wednesday, August 27, 2008 12:08 AM by trust20021

It's working perfect with me on win 2003(IIS6). After publishing it to our new Win2008(IIS7) It gave me the following error:

System.UnauthorizedAccessException was unhandled by user code

 Message="Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005."

 Source="App_Web_o3gwip7c"

This error occurs on the following line of code:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

Does anyone tried this on IIS7?

# re: Automating Microsoft Word 2007 with C Sharp

Wednesday, October 29, 2008 8:21 AM by Calm

thanx a lot, but how can I open word doc embedded in my winApp

# re: Automating Microsoft Word 2007 with C Sharp

Tuesday, November 11, 2008 4:43 PM by jfrojasdelrio

Hi there. It appears that working with automation always required to save/retrieve a file from the file system.

My situation is as follows: I uploaded a Word document and saved it into the database as a binary file. I don't have any problem showing the file again by using Response.BinaryWrite to the client. However, what I want is to add/modify this binaryfile before I render it to the client. I tried combining two binary arrays but it  didn't work. I came accross many articles that state that only through automation I can accomplish that. However, automation always require to save or retrieve files from the file system which it is not desirable for me.

Would you happen to know how to accomplish my goal?

Here is some code to give you all a head start:

     byte[] encodedBytes = myDocument.FileContents;

     int numBytes = btStr.Length;    

     int numBytes1 = myDocument.FileContents.Length;

     charArray1 = new char[uniCode.GetCharCount(

                                     encodedBytes, 0, numBytes1)];

     charArray = new char[uniCode.GetCharCount(

                                     btStr, 0, numBytes)];

     uniCode.GetChars(

               encodedBytes, 0, numBytes1, charArray1, 0);

     uniCode.GetChars(

                     btStr, 0, numBytes, charArray, 0);

     Response.Write(charArray1, 0, charArray1.Length);

     Response.End();

     Response.Flush();

# re: Automating Microsoft Word 2007 with C Sharp

Friday, November 14, 2008 8:13 AM by Xueliang

Is there any examples to embed a word document inside my own application?

# re: Automating Microsoft Word 2007 with C Sharp

Thursday, November 27, 2008 7:30 AM by Roopa

Hi,

Iam trying to get the content of document(.doc file) that is loaded in the winword control. but iam not able to get it with formatting.

winWordControl1.document.Content.Text   is returning plain text.

ex: "\rHello\r   How are You?\r\rAmbroxol\r\rAgrimycin \r\r\r\r\r\r\r"

The word "Ambroxol" is actually Bold. but i don't see a \b tag.

My task is to check the entire contents of document(without the user selecting it) using Spellex and replace the content with corrected words.  Can you help to get the content with format preserved?

# re: Automating Microsoft Word 2007 with C Sharp

Saturday, May 16, 2009 6:01 AM by Waseem Sindhu

I FIXED IT!!! Just launch (comexp.msc) and fixed permissions... Component Services-> Computers-> My Computer -> DCOM Config-> Microsoft Word Document-> Properties-> Security

1. Add NETWORK SERVICE to "Launch and Activation" with ALL checks enabled

2. Add NETWORK SERVICE to "Access Permissions" with BOTH checks enabled

Happy Coding,

Waseem

# re: Automating Microsoft Word 2007 with C Sharp

Monday, August 24, 2009 2:31 AM by neda

tank you very  much

# re: Automating Microsoft Word 2007 with C Sharp

Thursday, September 17, 2009 11:30 AM by J Staniforth

Hi Waseem,

I cannot find Microsoft Word Document in DCOM config?

I have Word 2007 installed - do you have a different version?

Do you have any other ideas why I cannot find it?

Cheers

Leave a Comment

(required) 
(required) 
(optional)
(required)