Reputation:
I managed to insert a text in a Bookmark of a Word document using Microsoft.Office.Interop.Word
.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(@"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
/* OR
doc.Bookmarks[bookmark].Select();
app.Selection.TypeText("Hello");
*/
The problem is this also opened the Word document. Can this be done without opening the document itself? Like its all happening in the background?
Upvotes: 1
Views: 1781
Reputation: 3537
Try using the Save
and Close
function after updating the text of the Bookmark of your Word Document.
Add the below code after the doc.Bookmarks.Add(bookmark, range);
.
doc.Save();
doc.Close();
EDIT:
If the computer is slow, the Word document might show within a second since you open it up. As hardcoregamer said, you can try to hide the object of Word.Application
first before opening it.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = false; //Hide the Word.Application object.
Document doc = app.Documents.Open(@"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
doc.Save(); //save the document.
doc.Close(); //close the document.
app.Quit(); //close the Word.Application object. otherwise, you'll get a ReadOnly error later.
Upvotes: 1