I am working on a word automation project in c# and am using the interop word library to read/write to word. I am currently using bookmarks in a word template doc to find where to write info to in the word doc from c#. One of my bookmarks consists of two highlighted lines in the doc. Based on a boolean value, i have to decide whether to leave that text there and add a new line of text right after it, or delete those existing two lines from the doc.
So here is my pseudo for it:
if (writeToDoc)
{
// leave selected bookmark text intact and press enter to write another line right after
}
else
{
//delete the selected bookmark text
}
Can anyone please show me how to delete existing text as well as do the equivalent of pressing enter and writing another line from c#?
Thanks
EDIT: Here is the code i have (roughly)
foreach (var bookmark in wordDoc.Bookmarks)
{
var bookMarkNameExistsInCode = listOfBookmarks.Contains(wordDoc.Bookmarks[bookmark].Name);
if (bookMarkNameExistsInCode )
{
object oBookMarkName = wordDoc.Bookmarks[bookmark].Name;
rng = wordDoc.Bookmarks.get_Item(ref oBookMarkName).Range;
// at this point i am pointing to the two selected lines labelled as a bookmark in word. How can i deselect and add a new line?
}
}
If the word manipulation is done on DocX files you could use DocX library and use some very simple commands like text.ReplaceText(); and other very easy/intuitive commands. Replacing Interop with DocX if possible should get you up and running in no time :)
Related
Note: I'm using Office Word 2007
I need to replace specific parts of a Word Document with comboboxes, checkboxes, text, etc..
I find "tags" using Regular Expression, and then iterate over regex Matches to get the specific text to replace.
var range = doc.Content; // where doc is current active word document
var matches = GetRegexMatches();
foreach (var match in matches){
if(range.Find.Execute(match.Value)){ // match.Value equals to the "tag" im searching
range.Collapse();
Word.ContentControl checkbox = range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckbox);
checkbox.Checked = true;
}
}
This code adds some weird box (I guess a ContentControl object, but not of type checkbox). Debugging it didn't help because it just stops the debugger.
I tried following another similar stackoverflow thread, but using a FormField instead of ContentControl just adds a grey checkbox which is disabled by default and unchangeable programatically.
Am I doing something wrong or it cannot be done in this Office version? Or both?
Apparently, if you are working with Office 2010+ and the document you're trying to open has been created in a version previous to the 2010, it gets opened in Compatibility Mode which disables many of the new functionalities in order to not break the file. That includes Comboboxes, Checkboxes, etc.. There's no workaround to this, other than opening the document in new Office version and saving it as newer version.
I am using the Novacode DocX c# library to create word documents and have run into a problem. I want my paragraphs to 'keep together' at page breaks. But, I also want to use soft returns to force my pictures to display vertically between lines of text.
So my question is, how do I add soft returns within paragraphs?
You can try to add one of those unicode char at the end of your paragraph, for instance :
using (DocX document = DocX.Create(#"docs\myDoc.docx"))
{
Paragraph p = document.Paragraphs[0];
p.Append("\u000D");
p.Append("\u000A");
}
Tell me if it solves your problem
I solved this with:
using (DocX document = DocX.Create(#"docs\myDoc.docx"))
{
Paragraph p = document.Paragraphs[0];
p.Append("\u000D");
}
Note: this is adapted from #G.Dealmeida's answer. If you include the additional \u000A then you get a second line break.
I'm creating a MsOffice template application(Winforms) to insert/evaluate the word document.
I want to insert a cover page and later after changes in cover page then i want to evaluate it, using interop c#. I searched a lot on internet but i didn't find suitable one.
Can any one please help me.
Thanks
So if your word template is the same (If the document already exists) each time you essentially have to:
Copy The Template
Work On The Template
Save In Desired Format
Delete Template Copy
Each of the sections that you are replacing within your word document you have to insert a bookmark for that location (easiest way to input text in an area).
I always create a function to accomplish this, and I end up passing in the path - as well as all of the text to replace my in-document bookmarks. The function call can get long sometimes, but it works for me.
Application app = new Application();
Document doc = app.Documents.Open("sDocumentCopyPath.docx");
if (doc.Bookmarks.Exists("bookmark_1"))
{
object oBookMark = "bookmark_1";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text =
"My Text To Replace bookmark_1";
}
if (doc.Bookmarks.Exists("bookmark_2"))
{
object oBookMark = "bookmark_2";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text =
"My Text To Replace bookmark_2";
}
doc.ExportAsFixedFormat("myNewPdf.pdf", WdExportFormat.wdExportFormatPDF);
((_Document)doc).Close();
((_Application)app).Quit();
The above code will get inserting text working for you - is there a reason that you have to re-evaluate the document afterwards if you know (and can add in checks before you attempt to insert ie: if the bookmark doesn't exist).
If you need some more explanation I can help as well :) my example saves it as a .pdf, but you can do any format you prefer.
I am working on a MS-Word addin that reads the content of a document and replaces every occurence of a specific word by a hyperlink.
So far, I came up with this working algorithm.
// Initializes the Find parameters
searchRange.Find.ClearFormatting();
searchRange.Find.Forward = true;
searchRange.Find.Text = "foo";
do
{
searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);
if (searchRange.Find.Found)
{
// Creates a Hyperlink at the found location in the current document
this.WordDocument.Hyperlinks.Add(searchRange, externalLink, link, "bar");
}
searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);
} while (searchRange.Find.Found);
This code works, however, it can be slow on bigger documents. Thus, instead of adding hyperlinks one by one, I wanted to simply to use the Find.Replacement object and with the WdReplace.ReplaceAllproperty.
However, I cannot manage to replace my search result by a Hyperlink.
Is there a way to replace a piece of text by a hyperlink using the Replacemethod ?
In other words, I'd like to find a way to do this :
Find.Replacement.Text = new Hyperlink(...);
On an other side, I've seen that, by hitting Alt + F9in Word, we can see hyperlinks as code.
The code looks like this :
{ HYPERLINK \l "link" \o "Caption" }
Another solution would be to be able to set the text replacement as that string and make Word interpret it and thus, create the link.
Thanks for reading.
As far as I know, fields can only be inserted programmatically, or by using CTRL-F9. There are two possible reasons for this that I see:
They are not simple text. They have two ranges, the Code and the Result, only one of which is displayed at any time.
How else would a user insert text that looks like a code but is not supposed to be one, unless there was a special mechanism to create one?
So let's say I have a program with just a text box and an okay button. The user types in whatever word he wants, and when he clicks ok, it opens a specific file called Test.doc and CTRL+F for the word "test" and replaces it with whatever the user entered into the text box. How can I open said file and replace instances of the word test with the user's defined word?
Ignoring the format of the document, you could literally use the folowing for any type of file:
var contents = System.IO.File.ReadAllText(#"C:\myDoc.doc");
contents = contents.Replace("Test", "Tested");
System.IO.File.WriteAllText(#"C:\myDoc.doc", contents);
The best way would be to use the ms office interop library though.
Andrew
A number of things:
I'd recommend using a FileDialog to get the file's location. This lets you select the file to edit, but also gives you functionality to only show the file types that you want to handle in this program.
If you're handling .doc's, I'd suggest you look into VSTO and opening word docs. Here's a guide I found after a quick search. I'd suggest using it as a place to start, but you'll need to look around for more specifics.
Lastly, the string.Replace("", ""); method is probably very helpful in the CTRL-F functionality. You should be able to extract a string of the text from whatever document you're analyzing and use that method.