TechRepublic

While the Microsoft Office suite still relies on VBA and COM, it may be utilised in .NET code via .NET and COM interoperability. This allows you to create more powerful applications by integrating the many functions available in the Word products into your application.

Developers often think they need they need to reinvent the wheel, when all they really need to do for certain tasks is make use of existing applications. A good example is utilising one or more applications in the Microsoft Office suite of products. For instance, you may want to utilise an Excel spreadsheet to create a chart or an expense report, or create a Word document that contains user-entered data. In this article, I'll examine integrating Word in a .NET application.

The programming model
It is strange that Microsoft pushes .NET as the ultimate solution, yet it is not utilised within the Microsoft Office programming model; Office still uses the older VBA (Visual Basic for Applications) model. A critical aspect of VBA is that it is based on COM (Component Object Model), so .NET and Microsoft Office cannot natively communicate with each other. However, a .NET feature called COM interop provides callable wrappers to allow .NET and COM to interoperate.

A runtime callable wrapper allows a COM component to be used by .NET. If you are using the Visual Studio .NET IDE, follow these steps:

  1. Select Add Reference from the Project menu.
  2. Select the COM tab of the Add Reference window and double-click the appropriate type library file listed.
  3. Select OK to end and add the reference.

At this point, Visual Studio .NET converts the objects and members in the COM type library file into equivalent .NET assemblies. Once the .NET assemblies are generated, you can easily instantiate classes and call members as if the COM objects and members were native .NET classes and members. This process may also be reversed so you can utilise a .NET assembly in a COM-based application, but that is beyond the scope of this article.

The process if further illustrated with an example. Let's create a Word document from a simple .NET Windows Form.

Using Microsoft Word
First, I create a new project within Visual Studio .NET and add a reference to the Microsoft Word type library. I am using Microsoft Word 2003, so the type library is Microsoft Word 11.0 Object Library. Once the reference is added, I can use the Word objects in the code. The VB.NET sample in Listing A opens an existing Word document from the local drive when the user clicks a button on the Windows Form.

Listing A
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Word
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim strFileName As String
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = word.Documents.Open("c:\test.doc")
doc.Activate()
Catch ex As COMException
MessageBox.Show("Error accessing Word document.")
End Try
End Sub
End Class

Here are a few notes about the code:

  • The System.Runtime.InteropServices namespace is imported to work with COM and .NET interoperability. It contains the COMException class.

  • The .NET wrapper for the Word objects is contained in the Microsoft.Office.Interop.Word namespace (the reference previously added to the project).

  • The Application class within the Word namespace is used to access the Word application.

  • The Document class within the Word namespace allows you to work with Word documents.

  • The Open method contained within the Documents property of the application allows an existing document to be loaded. It contains a Close method as well.

  • The Activate method of the Document class opens the document within a new instance of Word.

  • The code accessing the Word document is contained within a Try/Catch block. It catches COM errors via the COMException class. The MessageBox.Show method replaces the Office VBA MsgBox function.

Listing B contains the equivalent C# code.

Listing B
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace BuilderWordIntegration {
public class Form1 : System.Windows.Forms.Form {
private System.Windows.Forms.Button button1;
static void Main() {
System.Windows.Forms.Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e) {
Microsoft.Office.Interop.Word.Application word = null;
Microsoft.Office.Interop.Word.Document doc = null;
try {
word = new Microsoft.Office.Interop.Word.Application();
object  fileName = "c:\\test.doc";
object      falseValue = false;
object      trueValue = true;
object  missing  = Type.Missing;
word.Visible = true;
word.Activate();
doc = word.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.Activate();
} catch (COMException ex) {
MessageBox.Show("Error accessing Word document."); } } } }

The major difference in the C# code from the VB.NET version is the call to Documents.Open requires all parameters are passed to it, and these parameters must be references to objects. For this reason, objects are created and assigned values. Also, only references (ref) are passed to the method call. In addition, many of the parameters are null so the Type.Missing value is used in their place. In addition, the actual Word application must be activated via its own Activate method, and it must be displayed by setting its Visible parameter to true. The last caveat is that C# recognises the backslash (\) as an escape sequence, so double backslashes (\\) must be utilised to include a single one in a string.

Populating Word documents via .NET
You can open an existing Word document, or you may want to create a new Word document and populate it with data from an application. You can create a new Word document via the Add method of the Documents collection. The following VB.NET snippet uses the objects created in the previous example:

word.Documents.Add()

In addition, the Word Object Model includes numerous methods and properties for working with text within a Word document. The VB.NET example in Listing C creates a new document and inserts text in the beginning of the document when a button is selected (only the code for the button is shown).

Listing C
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim strFileName As String
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = word.Documents.Add()
Dim insertText As String = "Text inserted at the beginning of the document."
Dim range As Microsoft.Office.Interop.Word.Range = doc.Range(Start:=0, End:=0)
range.Text = insertText
doc.SaveAs("c:\test2.doc")
Catch ex As COMException
MessageBox.Show("Error accessing Word document.")
Finally
doc.Close(True)
End Try
End Sub

A few notes about this sample:

The Word.Range object allows you to work with a group or range of text within a Word document. The place within a document is specified by starting and ending values. In this example, the beginning of the document (start at zero) is used. An end value indicates the size of the range ââ,¬" zero indicates the beginning as well. The Text property of the Word.Range object allows the text to be set or reset. The SaveAs method allows you to save a document using the specified value. Listing D contains the C# equivalent.

Listing D
private void button1_Click(object sender, System.EventArgs e) {
Microsoft.Office.Interop.Word.Application word = null;
Microsoft.Office.Interop.Word.Document doc = null;
try {
word = new Microsoft.Office.Interop.Word.Application();
object  fileName = "c:\\test3.doc";
object      trueValue = true;
object  missing  = Type.Missing;
doc = word.Documents.Add(ref missing, ref missing, ref missing, ref trueValue);
string insertText = "Text inserted at the beginning of the document.";
Microsoft.Office.Interop.Word.Range range = null;
object startPosition = 0;
object endPosition = 0;
range = doc.Range(ref startPosition, ref endPosition);
range.Text = insertText;
doc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
} catch (COMException ex) {
MessageBox.Show("Error accessing Word document.");    } }

Once again, C# requires all parameters be specified so the Type.Missing value is utilised. You can browse the Word Object Model to learn more about the methods and properties available.

Another development tool
Microsoft Office is the most popular office suite in the world. You can easily integrate the power of the suite into your .NET application via .NET and COM interoperability. It opens a world of possibilities for adding powerful functionality to an application.

Do you need help with .Net? Gain advice from Builder AU forums

Related links

Comments

1

Steven Borwell-Fox - 02/08/05

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in WindowsApplication7.exe

Additional information: Cl****Factory cannot supply requested cl****

» Report offensive content

2

Roopesh - 10/08/05

Hi,

Word Range is a good concept.
1. But how we can access each page in the document.
2. How to read the content from a word document if a have word textboxes in the document.

TIA
-Roopesh

» Report offensive content

3

Anish - 12/08/05

4

sumit kumar chauhan - 28/09/05

hi friends,
this is a very simple C# code to read a word file with word formatting and without junk charecters.

In this code I simply used Clipbord to play with word data.

private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.Cancel)
return;

Word.ApplicationCl**** WordApp = new Word.ApplicationCl****();

object file = fd.FileName;
object nullobj = System.Reflection.Missing.Value;

Word.Document doc = WordApp.Documents.Open(
ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);

doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();
//Do whatever with the text.
string text = data.GetData(DataFormats.Text).ToString();

richTextBox1.Text = text;

//Close doc and shutdown Word application.
doc.Close(ref nullobj, ref nullobj, ref nullobj);
WordApp.Quit(ref nullobj, ref nullobj, ref nullobj);

}
Hope u like it!
Composed by
Sumit K Chauhan
Email: sumitkchauhan@hotmail.com

» Report offensive content

5

john - 10/11/05

I think this article is great, however I am having a naming conflict with System.Web and Word.System... I know I am not the first?

» Report offensive content

6

M - 01/12/05

I use the exact code posted. I add a reference to to the Library as recommended and I get;


The type or namespace name 'Interop' does not exist in the cl**** or namespace 'Microsoft.Office' (are you missing an ****embly reference?)

» Report offensive content

7

Prabhu - 22/12/05

Iam using the same code for opening and retrieving the contents of word document,but iam getting the error as "The Remote Procedure call failed" eventhough RPC is started and set as "Automatic" in my system.The error is coming in Quit statement.
help me...

» Report offensive content

8

Prabhu - 22/12/05

Iam using the same code for opening and retrieving the contents of word document,but iam getting the error as "The Remote Procedure call failed" eventhough RPC is started and set as "Automatic" in my system.The error is coming in Quit statement.
help me...

» Report offensive content

9

munns - 02/08/06

How to read a word document from a web form?

» Report offensive content

10

sanjay sharma - 18/08/06

hi
currently i am doing a project and i got a problem----- that how can i access the scanned image which is scanned by scanner.
and i want to use that text in the .net application.

plz mail me soon if any body know that how to solve it
my mail id is---------sanjay_arya232000@yahoo.co.in

» Report offensive content

11

king - 24/08/06

I have a word template which we manually fill in. I want to create a form in .net where you type the data and press a button and it updated a word template with that data. Any ideas?

» Report offensive content

12

Akeel - 01/09/06

Following code works fine to read text from a word file and return the extracted text, when used in C# Windows application. But it raises a runtime exception (NullReference Exception) at line
string text = data.GetData(DataFormats.Text).ToString();
when used in ASP.NET/C# application. I am unable to find out why is this. Is there any solution for this ?

Thanks and Regards,
Akeel

      Word.ApplicationClass WordApp = new Word.ApplicationClass();
object file = FilePath;
object nullobj = System.Reflection.Missing.Value;
Word.Document doc = WordApp.Documents.Open(
ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj);

doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();
doc.Close(ref nullobj, ref nullobj, ref nullobj);
WordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
return text;

» Report offensive content

13

Morupisi - 06/09/06

I NEED HELP [using VB.NET]

Can you please help: how can i capture a string of text from a word document and compare it with text from other document. Also how can i take that text from one microsoft word document and use a search engine like google and google with that string of text, still using VB.NET, does anyone have an idea, if so communicate with me ASAP.

email:mmorupisi@gmail.com

» Report offensive content

14

Ajay Sawant - 11/09/06

Try using DSO Framer [Free activeX control from microsoft]

Download Link = http://support.microsoft.com/?id=311765

Cheers

» Report offensive content

15

Muwaddat Jafffri - 22/09/06

Thanks for thr article. However, I did all the steps as mentioned here but get the following warning:
Warning 1 Namespace or type specified in the Imports 'Microsoft.Office.Interop.Word' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.

...for the "Imports Microsoft.Office.Interop.Word" statement

This results in errors when I type the following :
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document

with the word.application and word.document being undefined.

I added the reference and can even see it in the references in the solution explorer.
Thanks in advance.

» Report offensive content

16

Muwaddat Jaffri - 13/10/06

Regarding my comment above. The errors can be removed by not using interop.word and only word. E.g.
Imports Microsoft.Office.Interop.Word
should be
Imports Microsoft.Office.Word
Cheers

» Report offensive content

17

AbdulAleem - 17/11/06

Dear Friends, Can u pls. tell me which versions of Internet Explorer and Mozilla support DSO Framer control. If they are supporting what settings have to be made to them, pls. give me all the information pls. Because its a requirement from my client. I have to answer him clearly. So pls. answer me ASAP. You can even mail me to : aleem_abdul@akebonosoft.com.
Aleem

» Report offensive content

18

Maxim - 21/11/06

Does it work differently in Win2K? I added the reference and still don't have Microsoft.Office.Interop namespace. Does anyone know what's the problem?

» Report offensive content

19

Steve - 22/11/06

Consider removing the word "utilise" from your article. You use it 8 times. I was taught to never use that word, since it is an exact synonym for the word "use", it just has more syllables and sounds like you're trying to be overly-technical or use buzzwords.

» Report offensive content

20

marius - 25/11/06

Hi ! I have a word document that contains formfields ,and I want to fill the formfields (gray areas) with content of Textbox on my application form . In VB6 I can use successfully this item:.FormFields("name") = TextBox1.Text where "name" is the name of an bookmark of the text form fields in my Word Doc.
I can't do the same in the VB.Net. Can you help me, please ?
Any help will be greately appreciatted. Thanks

» Report offensive content

21

Saurabh - 28/11/06

The code works fine to read text from a word file and return the extracted text, but I need to extract the image embedded in that word file.

» Report offensive content

22

Saurabh - 28/11/06

The code works fine to read text from a word file and return the extracted text, but I need to extract the image embedded in that word file.

» Report offensive content

23

Saurabh - 28/11/06

The code works fine to read text from a word file and return the extracted text, but I need to extract the image embedded in that word file.

» Report offensive content

24

Nasim - 12/12/06

Hi, I am wondering how I can perform 'find and replace' text in a word documennt . I will appreciate your response.

» Report offensive content

25

Lalit Doshi - 13/01/07

pls...help me in my project

How i can fetch word - by- word form the text file(.doc,.txt. , .pdf., etc...) in C#.Net Application using microsoft Office.interop....

any body has idea about that then pls.. reply me.....

my E-mail Id is : Lakulishdoshi@yahoo.co.in

» Report offensive content

26

shalu - 16/01/07

hello frnds plz help me
now i am doing my final project.can u tell me how to parse a resume in the word document form which is send to a company.ie separating the fields like name,emailid,academic merit,experianceand skills from an resume.

» Report offensive content

27

Nagaraju - 31/01/07

Hi i have gone through ur question i too finding that but till now i did nt got anything if u find plz forward it to me

» Report offensive content

28

Phil Weeks - 01/02/07

Why do you have to make word.Visible=true?

I'd rather not have word popping open when i process the document for my user, but if i set it to false, i get an error opening the document.

Also someone asked but i didnt see a reply, how do you retrieve the section numbers from a heading?

If I have 5.2.2.1 Some Heading Text

how do i get the 5.2.2.1 and the text?

» Report offensive content

29

Trafmore - 07/02/07

This is some really cool stuff. I have one question. How would save the doc file to an sql database?

» Report offensive content

30

zawmn - 15/02/07

I need to delete the first page of a word document. How can I do it in vb.net.

» Report offensive content

31

dharani - 10/03/07

Hi Friends,

i need an idea

am doing project in E-learning..in that am doing Online Assignments..

for ex .am typing one topics in a textbox.
and in another textbox am typing some content related to that topics..

based on that ,system must automatically review that whether the content is related to that topics?..
how to do that?i want that in VB.NET or C#
if u have any idea ,send me ASAP..

» Report offensive content

32

Minadd - 12/03/07

Hello,
I am using VC.Net 2003 version 7.1, I am trying to run MS word 2003 as a part of the the windows Form. I have followed the instructions to add reference to Ms word object..11.
When I type Microsoft::Office::Word::Document * wdSummary; there is a compiler error "Word is not a member of Microsoft office".
How do I solve this?
Thanks for your help.

» Report offensive content

33

Minad - 12/03/07

Hello,
I am using VC.net 2003, version 7.1.
I am trying to run Ms word 2003 as part of the windows form.
I added a reference to MS Word Object 11.0, it gets built successfully but when I type Microsoft::Office::Interop ::Word::Document * wdSummary and complie there is an error " Interop is not a member of Microsoft".
How do I solve this ? Please help!

» Report offensive content

34

I need help - 23/03/07

how to draw a table sturcture in word using interop in .net

» Report offensive content

35

toko - 25/03/07

how to save word document to HTML file using C#

» Report offensive content

36

prasad - 16/04/07

Hi
iam using ms word 2003 i nedd if else conditional statements
in word document with inteligence just ike we use it in .net ide
how do solve this

» Report offensive content

37

mahendra - 07/06/07

hi freinds
all of the above code is very excellent but problem is same
as ABOVE COMMENTS
THAT WE ARE USING SAME OBJECT REFERENCE AS TOLD IN CODE BUT IS GIVIN ERROR

Dim word_server As New Word.Application

tyPE WORD APPLICATION IS NOT DEFINED
AND IF WE WANT TO DEFINE ABOVE
SO I AM USING


Imports System.Runtime.InteropServices

Imports Microsoft.Office.Core ??????

I AM GETTING CORE NOT WORD OR NOT ANY OTHER OPTION BUT IN CODING U HAD USED OTHER WORD AND MANY MORE OPTION

PLZZZZ TELL ME HOW CAN I REMOVE THIS PROBLEM

BYE

 Dim word_server As New Word.Application

» Report offensive content

38

bm - 26/06/07

HI
I used C#.net to modify the content of word document.
From a form,i open the word file and extract the text and make operation to text.but the resulted text is missing format such as bold,italic.
How can i maintain the text format as original document.
Thank you

» Report offensive content

39

die_nadel - 02/07/07

On word document some of it use cells. On that particular cell has an input value. How can I read each cell content, get it and transfer it to the database for example.
Since I'm new in VB.net is it possible?

» Report offensive content

40

Yusuf Shabbir - 19/07/07

Hello Everybody,
I hav a problem relating to Placing Image content in a Word Document. My Image is a BarCode with some Text Contents, whenever i place the Image in a Word Document the Image Appears upside Down and the BarCode Text overlaps the Barcode Image.
Im using the InlineShape.AddPicture method to Place Image in a Word Document.
Suggestion required at the earliest

Thank You
Bye


Word.InlineShape isBarcodeShape;
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
objWordDoc.Content.Collapse(ref oCollapseEnd);
isBarcodeShape = objWordDoc.ActiveWindow.Selection.Range.InlineShapes.AddPicture(strTempPath + "BarcodePicture.bmp", ref missing, ref missing, ref missing);

» Report offensive content

41

Abe - 31/07/07

Is their a plugin where I can use spell check on a rich textbox or do I have to just code it my self this code just opens up microsoft word wich I do not want to do. I already have a dictionairy that I have paid for I guess I will just have to do it all.

» Report offensive content

42

Benjamani - 23/08/07

This sample works great!

To Steve: Utilize and Use are different words in the dictionary. Learn the difference before criticizing.

To S***: To save the Word document to a SQL database, you have to store the binary stream in manageable chunks. It works great!

» Report offensive content

43

Benjamani - 23/08/07

This sample works great!

To Steve: Utilize and Use are different words in the dictionary. Learn the difference before criticizing.

To S***: To save the Word document to a SQL database, you have to store the binary stream in manageable chunks. It works great!

» Report offensive content

44

narayana - 29/08/07

i'm not able to create an object for word application or word document.. when i used Imports Microsoft.Office.word or Imports Microsoft.Office.Interop.Word. i'm getting an error as Namespace or type specified in the Imports 'Microsoft.Office.Interop.Word' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases... how can i create the object for word.. is there any namespaces or references are to be added

» Report offensive content

45

Ayyanar - 03/09/07

Hi,

I have a word document that has attached(ie. embedded ) documents like word, ppt, pdf, etc.

I have to extract those embedded documents in the document through code.

To extract embedded word document. I used the following code.

I need help to extract other types of documents(generally all type of attachments).

Please advice.

CODE:
---------

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



doc = word.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

doc.Activate();

int attachmentsCount = doc.InlineShapes.Count;

for (int i = 0; i < attachmentsCount; i++)

{

embedDoc = doc.InlineShapes;

tempDoc = (Document)embedDoc.OLEFormat.Object;

tempDoc.SaveAs(ref tempFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);


}

» Report offensive content

46

kwek - 16/09/07

I am new to VB.net. Curretly i working with my final year project. Nw i need to read and find the content from the doc file in web based application. I have to read the whole content of the doc file.And will start to find the content from the references below.

Example:






********

other content

********
REFERENCE

[1] L. Bernstein, âGet The Design Rightâ. IEEE Software, Vol. 10 No. 5, September 1993, pp. 61-63.

[2] Z. Razak, âThe Internet Global Villagesâ, in Using IT to Build a Better Future Conference, Kuala Lumpur, 3 October 1995.


i need to get content within quotes â â from the references which is the title. Is there any example code to read and search all the "title" from doc.

I am trying Interop.Word where you suggested url Understanding the Word Object Model from a .NET Developer's Perspective. There are some problem i cant solve. The code can compile without an error .Bt no result come out.



Example Of Code (Just want to get the doc content)



Dim myWordDoc As Word.Document

Dim myWord As Word.Range

myWordDoc = myWordApp.Documents.Open(Server.MapPath("Doc\test.doc"))

For Each myWord In myWordDoc.Sentences

If InStr(myWord.Text, "REFERENCES", CompareMethod.Text) <> 0 Then

myWordDoc.Range(ThisDocument.Sentences(myWordDoc.Sentences.Count).Start, ThisDocument.Sentences(myWordDoc.Sentences.Count).End)

Me.txtContent.Text = String.Format(Format, myWordDoc.Sentences.First)

bolFound = True

Exit For

End If

Next

myWordDoc = myWordApp.ActiveDocument

myWord = myWordDoc.Range(0, 5)

myWord.Select()

Me.txtContent.Text = myWord.Text

myWordDoc.Close() 'close the word doc

myWordApp.Quit() 'Quit the word app

myWord = Nothing

myWordDoc = Nothing



Please help me.

Is there any note or tutorial that i can refer to.?

Thanks

» Report offensive content

47

Umesh Thakral - 12/10/07

About VB.NET
hi friend i have inseted the text in word file now i have to append the table in the active word document but it remove the text and add the table to that document. So i have to get the reference or range of the previous entered text so that i can append the table to document.. So how i do this....

» Report offensive content

48

lewis - 18/11/07

I am trying to create a bookmark within the word document, then a hyperlink back to that bookmark from elsewhere in the document.

I can add the bookmark to the collection but I can't create the hyperlink.

Any ideas?

oRng = oDoc.Bookmarks.Item("\endofdoc").Range
oRng.Collapse(word.WdCollapseDirection.wdCollapseEnd)
oRng.InsertBreak(word.WdBreakType.wdPageBreak)
oRng.Collapse(word.WdCollapseDirection.wdCollapseEnd)
oRng.InsertAfter(fldName)
oRng.Font.Bold = True
oRng.ParagraphFormat.SpaceAfter = 24
oRng.InsertParagraphAfter()
oDoc.Bookmarks.Add("a", oRng)




oTable.Cell(r + 1, 1).Range.Text = fldName
oTable.Cell(r + 1, 1).Select()

oDoc.Hyperlinks.Add(oWord.Selection, , "a")

» Report offensive content

49

Itai Schechter - 20/12/07

Hi ,
I have 2 questions ....
1) How do I insert a picture to the documnet ??
2) How do i switch from Right-to-Left TO Lesft-to-right ??

10x Inadvance,
Itai Schechter.

» Report offensive content

50

ROOPA - 29/12/07

i want to attach ms word document by using open file dialog box.
how i do that

» Report offensive content

51

lds - 09/01/08

mahendra - did you ever figure out why you are getting Microsoft.Office.Core instead of Microsoft.Office.Interop.Word. I am having the same problem

» Report offensive content

52

Kaikookoo - 11/01/08

Posible that I embedde word into C# windows form

Thanks ^-^

» Report offensive content

53

Daniel Ciornei - 07/02/08

If I want do drag some text in the Word control, how can I capture the Drag & Drop Event of the Word Control

» Report offensive content

54

Peter Bevil - 15/02/08

Hi everybody. My name's Peter from Buenos Aires. I'm using DSOFramer control to merge office documents stored in SQl Server, their classification data and another info and then Print or perfomr print preview. I can share all my code to someone that helps me to digitally sign the DSOFramer control using the "Trial certificate that generates the Microsoft Certificates Server. (a non comercial certificate - Don't want to pay for a certificate because my ASP application is intranet use for corporations). Any help welcomed. Best wishes to you all programmers of the world!!!

» Report offensive content

55

Peter Bevil - 15/02/08

oh, I forgot: martin@workflow.com.ar. See Comment #55

» Report offensive content

56

Bhaskar - 03/03/08

its agreat one can u help me on ms word in .net
in my project i want to attach ms-word document to a form,
and i want to add some text info to that ms-word document(with appending text ) plz help me

regards
Bhaskar
medikondu.bhaskar@gmail.com

» Report offensive content

57

Tushar Kale - 19/07/08

Very Nice Article......But How was the .doc file are generate in listbox control......

» Report offensive content

58

sheryar Nizar - 21/07/08

This can also be done by the following CODE

From
Sheryar Nizar
http://www.sheryar.net

private bool PrintDocument(string universityCode, string documentCode)
{
//string FilePath = @"C:\MUST Templates\welcomeLetter.doc";
string FilePath = AppSettings.TemplatePath + universityCode + @"\" + documentCode + ".doc";
string CopyFile = FilePath.Insert(FilePath.LastIndexOf('.'), "_Copy");
File.Copy(FilePath, CopyFile);

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass();

object nullobj = System.Reflection.Missing.Value;

object file = CopyFile;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc.Content.Text = doc.Content.Text.Replace("VAR_STUDENT_ID", STUDENT_ID)
.Replace("VAR_STUDENT_NAME", STUDENT_NAME)
.Replace("VAR_DATE_OF_BIRTH", DATE_OF_BIRTH)
.Replace("VAR_STUDENT_ADDRESS", STUDENT_ADDRESS)
.Replace("VAR_STUDENT_PHONE", STUDENT_PHONE)
.Replace("VAR_TOLL_FREE_NO_1", TOLL_FREE_NO_1)
.Replace("VAR_TOLL_FREE_NO_2", TOLL_FREE_NO_2)
.Replace("VAR_STUDENT_EMAIL", STUDENT_EMAIL)
.Replace("VAR_STUDENT_PICTURE", STUDENT_PICTURE)
.Replace("VAR_VALID_UNTIL", VALID_UNTIL)
.Replace("VAR_ISSUED_ON", ISSUED_ON)
.Replace("VAR_DATE_OF_COMPLETION", "")
.Replace("VAR_DATE_OF_WITHDRAWAL", DATE_OF_WITHDRAWAL)
.Replace("VAR_MAJOR_NAME", MAJOR_NAME)
.Replace("VAR_SCHOOL_NAME", SCHOOL_NAME)
.Replace("VAR_PROGRAM_NAME", PROGRAM_NAME)
.Replace("VAR_COURSE_NAME", COURSE_NAME)
.Replace("VAR_DEGREE_NAME", DEGREE_NAME)
.Replace("VAR_PROGRAM_CATEGORY_TYPE", PROGRAM_CATEGORY_TYPE)
.Replace("VAR_ENROLLMENT_DATE", ENROLLMENT_DATE)
.Replace("VAR_REFERENCE_CODE", REFERENCE_CODE)
.Replace("VAR_STUDENT_PREVIOUS_NAME", STUDENT_PREVIOUS_NAME)
.Replace("VAR_FIRST_NAME", STUDENT_FIRST_NAME)
.Replace("VAR_MIDDLE_NAME", STUDENT_MIDDLE_NAME)
.Replace("VAR_LAST_NAME", STUDENT_LAST_NAME)
.Replace("VAR_DEGREE_LEVEL", DEGREE_LEVEL)
.Replace("VAR_CGPA", CGPA)
.Replace("VAR_START_DATE", PROGRAM_START_DATE)
.Replace("VAR_PROGRAM_END_DATE", PROGRAM_END_DATE)
.Replace("VAR_STUDENT_PRESENT_NAME_FROM_DATE", STUDENT_PRESENT_NAME_FROM_DATE)
.Replace("VAR_STUDENT_PREVIOUS_NAME_FROM_DATE", STUDENT_PREVIOUS_NAME_FROM_DATE)
.Replace("VAR_STUDENT_PREVIOUS_NAME_TO_DATE", STUDENT_PREVIOUS_NAME_TO_DATE)
.Replace("VAR_EMPLOYER_NAME", EMPLOYER_NAME)
.Replace("VAR_EMPLOYER_ADDRESS", EMPLOYER_ADDRESS)
.Replace("VAR_EXT", PHONE_EXT)

.Replace("V1", COURSE_CODE[0])
.Replace("VGC1", GENERAL_COURSE_NAME[0])
.Replace("H1", CREDIT_HOURS[0])
.Replace("GP1", GPA[0])

.Replace("V2", COURSE_CODE[1])
.Replace("VGC2", GENERAL_COURSE_NAME[1])
.Replace("H2", CREDIT_HOURS[1])
.Replace("GP2", GPA[1])

.Replace("V3", COURSE_CODE[2])
.Replace("VGC3", GENERAL_COURSE_NAME[2])
.Replace("H3", CREDIT_HOURS[2])
.Replace("GP3", GPA[2])

.Replace("V4", COURSE_CODE[3])
.Replace("VGC4", GENERAL_COURSE_NAME[3])
.Replace("H4", CREDIT_HOURS[3])
.Replace("GP4", GPA[3])

.Replace("V5", COURSE_CODE[4])
.Replace("VGC5", GENERAL_COURSE_NAME[4])
.Replace("H5", CREDIT_HOURS[4])
.Replace("GP5", GPA[4])

.Replace("V6", COURSE_CODE[5])
.Replace("VGC6", GENERAL_COURSE_NAME[5])
.Replace("H6", CREDIT_HOURS[5])
.Replace("GP6", GPA[5])

.Replace("V7", COURSE_CODE[6])
.Replace("VGC7", GENERAL_COURSE_NAME[6])
.Replace("H7", CREDIT_HOURS[6])
.Replace("GP7", GPA[6])

.Replace("V8", COURSE_CODE[7])
.Replace("VGC8", GENERAL_COURSE_NAME[7])
.Replace("H8", CREDIT_HOURS[7])
.Replace("GP8", GPA[7])

.Replace("V9", COURSE_CODE[8])
.Replace("VGC9", GENERAL_COURSE_NAME[8])
.Replace("H9", CREDIT_HOURS[8])
.Replace("GP9", GPA[8])

.Replace("V10", COURSE_CODE[9])
.Replace("VGC10", GENERAL_COURSE_NAME[9])
.Replace("H10", CREDIT_HOURS[9])
.Replace("GP10", GPA[9])

.Replace("V11", COURSE_CODE[10])
.Replace("VGC11", GENERAL_COURSE_NAME[10])
.Replace("H11", CREDIT_HOURS[10])
.Replace("GP11", GPA[10])

.Replace("V12", COURSE_CODE[11])
.Replace("VGC12", GENERAL_COURSE_NAME[11])
.Replace("H12", CREDIT_HOURS[11])
.Replace("GP12", GPA[11])

.Replace("V13", COURSE_CODE[12])
.Replace("VGC13", GENERAL_COURSE_NAME[12])
.Replace("H13", CREDIT_HOURS[12])
.Replace("GP13", GPA[12])

.Replace("V14", COURSE_CODE[13])
.Replace("VGC14", GENERAL_COURSE_NAME[13])
.Replace("H14", CREDIT_HOURS[13])
.Replace("GP14", GPA[13])

.Replace("V15", COURSE_CODE[14])
.Replace("VGC15", GENERAL_COURSE_NAME[14])
.Replace("H15", CREDIT_HOURS[14])
.Replace("GP15", GPA[14])

.Replace("V16", COURSE_CODE[15])
.Replace("VGC16", GENERAL_COURSE_NAME[15])
.Replace("H16", CREDIT_HOURS[15])
.Replace("GP16", GPA[15])

.Replace("V17", COURSE_CODE[16])
.Replace("VGC17", GENERAL_COURSE_NAME[16])
.Replace("H17", CREDIT_HOURS[16])
.Replace("GP17", GPA[16])

.Replace("V18", COURSE_CODE[17])
.Replace("VGC18", GENERAL_COURSE_NAME[17])
.Replace("H18", CREDIT_HOURS[17])
.Replace("GP18", GPA[17])

.Replace("V19", COURSE_CODE[18])
.Replace("VGC19", GENERAL_COURSE_NAME[18])
.Replace("H19", CREDIT_HOURS[18])
.Replace("GP19", GPA[18])

.Replace("V20", COURSE_CODE[19])
.Replace("VGC20", GENERAL_COURSE_NAME[19])
.Replace("H20", CREDIT_HOURS[19])
.Replace("GP20", GPA[19])

.Replace("V21", COURSE_CODE[20])
.Replace("VGC21", GENERAL_COURSE_NAME[20])
.Replace("H21", CREDIT_HOURS[20])
.Replace("GP21", GPA[20])

.Replace("V22", COURSE_CODE[21])
.Replace("VGC22", GENERAL_COURSE_NAME[21])
.Replace("H22", CREDIT_HOURS[21])
.Replace("GP22", GPA[21])

.Replace("V23", COURSE_CODE[22])
.Replace("VGC23", GENERAL_COURSE_NAME[22])
.Replace("H23", CREDIT_HOURS[22])
.Replace("GP23", GPA[22])

.Replace("V24", COURSE_CODE[23])
.Replace("VGC24", GENERAL_COURSE_NAME[23])
.Replace("H24", CREDIT_HOURS[23])
.Replace("GP24", GPA[23])

.Replace("V25", COURSE_CODE[24])
.Replace("VGC25", GENERAL_COURSE_NAME[24])
.Replace("H25", CREDIT_HOURS[24])
.Replace("GP25", GPA[24])

.Replace("V26", COURSE_CODE[25])
.Replace("VGC26", GENERAL_COURSE_NAME[25])
.Replace("H26", CREDIT_HOURS[25])
.Replace("GP26", GPA[25])

.Replace("V27", COURSE_CODE[26])
.Replace("VGC27", GENERAL_COURSE_NAME[26])
.Replace("H27", CREDIT_HOURS[26])
.Replace("GP27", GPA[26])

.Replace("V28", COURSE_CODE[27])
.Replace("VGC28", GENERAL_COURSE_NAME[27])
.Replace("H28", CREDIT_HOURS[27])
.Replace("GP28", GPA[27])

.Replace("V29", COURSE_CODE[28])
.Replace("VGC29", GENERAL_COURSE_NAME[28])
.Replace("H29", CREDIT_HOURS[28])
.Replace("GP29", GPA[28])

.Replace("V30", COURSE_CODE[29])
.Replace("VGC30", GENERAL_COURSE_NAME[29])
.Replace("H30", CREDIT_HOURS[29])
.Replace("GP30", GPA[29]);
doc.Content.AutoFormat();
Microsoft.Office.Interop.Word.Range range = null;





doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
doc.ActiveWindow.PrintOut(ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);

File.Delete(CopyFile);
InitializePrinting();
return true;
}

» Report offensive content

59

Shawn - 29/07/08

Thank you very much for taking the time to write & post the article!

» Report offensive content

60

Huynh Cao Ky - 08/08/08

Thank you sheryar Nizar.

» Report offensive content

61

swarupa - 20/08/08

good code for extracting word in .net

Extracting  Header of our Document  in .net

» Report offensive content

62

Felipe - 04/09/08

hi !! Banda, i have cuestion, did you know how can paste one document word in a Textbox, well i using vb.net 2008 and asp, i hope some one can help me!!
TNX

» Report offensive content

63

vijayakumar - 13/11/08

Hi Guru's

Please ref. my code below. i am opening a word document and reading the text content and storing into a textbox and closing the application. my problem is when i am running the code it is closing the word application properly. But after hosting into my local / web server the winword applicaion not closing i can see in process so many times. (task manager)

Software vs2005
OS xp professional

please kindly help me in this regard
vijay

Dim app As New Microsoft.Office.Interop.Word.Application
Dim doc As New Microsoft.Office.Interop.Word.Document

doc = app.Documents.Open("\\server\copy\" & Trim(ddlcustomer.SelectedItem.ToString) & "\" & Trim(ddljournal.SelectedItem.ToString) & "\" & Trim(ddlarticleid.SelectedValue) & "\queries.doc")
app.Visible = False
doc.Activate()
doc.ActiveWindow.Document.SaveAs("\\server\copy\" & Trim(ddlcustomer.SelectedItem.ToString) & "\" & Trim(ddljournal.SelectedItem.ToString) & "\" & Trim(ddlarticleid.SelectedValue) & "\queries.txt", 4)
mbody = mbody & doc.ActiveWindow.Document.Content.Text
app.ActiveDocument.Close()
app.Application.Quit()
doc = Nothing
app = Nothing
txtbody.Text = mbody

» Report offensive content

64

reza - 16/11/08

how can i read textbox that exist in word(.doc) file or fill one label that existing in file with dynamic data. in word 2007 can do it with ContentControl but this instrument does not exists in word2003. please help me.

» Report offensive content

65

Krish - 04/02/09

I found a solution to "Compare Microsoft Word 2007 Documents" in .Net

e.g. we want to compare a.docx with b.docx. We don't want to open and read those files, we only want to compare them. The beauti of this code is, it doesn't ask the user to open the files in "Readonly" mode, even if the files are kept opened somewhere.

I thought it might be useful to you guys.

Thanks,
Krish

Imports statement:
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Word

Code:
Dim strFileName As String = "c:\a.docx"
Dim strRevisedFileName As String = "c:\b.docx"
Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc_compare As Microsoft.Office.Interop.Word.Document
Dim doc1 As Microsoft.Office.Interop.Word.Document = Nothing
Dim doc2 As Microsoft.Office.Interop.Word.Document = Nothing
Try
Dim falseValue As Object = False
Dim trueValue As Object = True
Dim missing As Object = Type.Missing
word.Visible = False
doc1 = word.Documents.Open(strFileName, missing, trueValue, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
doc2 = word.Documents.Open(strRevisedFileName, missing, trueValue, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)

word.Visible = True
doc_compare = word.CompareDocuments(doc1, doc2)
doc_compare.Activate()

Catch ex As COMException
MessageBox.Show("Error accessing Word document." & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & ex.Source & vbCrLf & vbCrLf & ex.StackTrace)
Finally
doc1.Close()
doc2.Close()
doc_compare = Nothing
End Try

» Report offensive content

66

Krish - 04/02/09

Hi there,

One thing, I forgot to mention:

You would want to write below line to bring the word actively on screen:

word.Activate()

Thanks,
Krish
a4acharya@gmail.com

» Report offensive content

67

Adriano - 05/02/09

Hi, I see don't have spellchecker.
I adapted the code.
Good Luck.

private void btoCorrigir_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

object visivel = false;
object missing = Type.Missing;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref visivel);

doc.Words.First.InsertBefore(TextBox.Text);

doc.CheckGrammar();
doc.CheckSpelling(ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);

object primeiroCaracter = 0;
object ultimoCaracter = doc.Characters.Count - 1;

TextBox.Text = doc.Range(ref primeiroCaracter,ref ultimoCaracter).Text.Replace("\r",Environment.NewLine);

object salvarAlteracoes = false;
doc.Close(ref salvarAlteracoes, ref missing, ref missing);
app.Quit(ref salvarAlteracoes, ref missing, ref missing);
}

» Report offensive content

68

CoolGuyZ - 09/02/09

Hi Guru's

I need to open a word document and reading the text content. My program will be running successfully when i ran it under administrator account. But when I run my application using the application pools account , it fails without throwing any error .

The particular code that fail to run is :
Dim newApp As New Microsoft.Office.Interop.Word.Application()

From the task manager, i can see that the WINWORD.exe is running under the application pools account that is assigned to the application. I have verified that the word application can be launch manually using the application pools account and in the Component Services, I have granted the permission for the application pools account to Local Launch , remote launch, local activation, remote activion

Any idea how to solve this issue ? what kind of permission ?

Kindly advice

Thanks

» Report offensive content

69

vasanth.c - 26/03/09

Hai everybody,
iam new to this forum.
Anybody have idea about how to parse a resume in the word document.
Form that resume we separating the fields like name,emailid,experiance and skills.
After that the Seprated fields Automatically store in the Database

pls help me

» Report offensive content

70

arun - 08/10/09

Hi,

I am creating an asp.net application, in which some word files(word 2007) will be available in server side. The user can edit the word files and resend it to server.

For this i have sent the word xml from server through response with content type as msword, and it will be opened in a new word instance in client side. User can edit this document.

In client machine there will be one word addin, which will contain 'Post' button, by pressing this post button i need to post the updated word xml to server using the same session. Is this possible? Can any one help me?

Yours,
Arun

» Report offensive content

71

James - 26/02/10

I'm working with the PIA for Word and MSProject a lot in this application I'm working on. Everything concerning Word works pretty much flawlessly except every time I try to call .Save() or .SaveAs() I get the COMException listed below.

Also, even if I comment out the .Save() and close my program then switch over to Word and try to save the document manually, I get a crash in Word too.

Any ideas?

Thanks
James

System.Runtime.InteropServices.COMException occurred
ErrorCode=-2147417851
Message="The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"
Source="Microsoft.Office.Interop.Word"
StackTrace:
at Microsoft.Office.Interop.Word.DocumentClass.Save()
at Project_Automation.Form1.cmdFinishDocument_Click(Object sender, EventArgs e) in C:\Users\matt.p.hartman\Desktop\08-03-09 SWA - Reqwrite Project interface code\Project Automation\Form1.vb:line 16201

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

71

James - 26/02/10

I'm working with the PIA for Word and MSProject a lot in this application I'm working on. Everything concerning Word works ... more

70

arun - 10/08/09

Hi, I am creating an asp.net application, in which some word files(word 2007) will be available in server side. The user can ... more

69

vasanth.c - 26/03/09

Hai everybody, iam new to this forum. Anybody have idea about how to parse a resume in the word document. Form that resume ... more

Log in


Sign up | Forgot your password?

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

  • Staff Microsoft showcases new NUIs

    TechFest, Microsoft's internal even took place this week with researchers showcasing some new interfaces the company is working on. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!