Reputation: 528
I want to open an existing MS Word document, then write a specific text on it.
The existing document has this content:
First car costs ... $.
I would like to add a specific text right after the word costs. The final text should be :
First car costs 15000 $.
I want to do this using a simple c# application. I'm having difficulties to find a way to add text at the desired position.
I used a NuGet package called DocX. Here is my code:
using Novacode;
using System.Text.RegularExpressions;
...
string fileName = @"C:\Users\DAFPC\Documents\WordDoc1.docx";
var doc = DocX.Load(fileName);
doc.ReplaceText("...", "15000",false, RegexOptions.None, null, null, MatchFormattingOptions.SubsetMatch, true, false);
doc.Save();
Process.Start("WINWORD.EXE", fileName);
The code does not replace "..." with "15000". But if I try to replace the word "Car" with "15000" the code works.
Upvotes: 1
Views: 980
Reputation: 1250
Check edit
doc.ReplaceText(toReplace, replacement);
You should wrap it in a function like the following:
static void Main(string[] args)
{
string filename = "test.docx";
ReplaceInDocx(filename, "...", "15000");
}
static void ReplaceInDocx(string filename, string toReplace, string replacement)
{
var doc = DocX.Load(filename);
doc.ReplaceText(toReplace, replacement);
doc.Save();
}
You might find this useful.
Edit: Ok, I see what you mean. The problem is with the way MS Word works. When you enter "..." it automatically gets converted into "…" (ellipsis). What you should do, then, is to search for that instead. Or better, change the search parameter.
ReplaceInDocx(filename, "…", "car");
Upvotes: 2