I have created a docx file from a word template, now I am accessing the copied docx file and want to replace certain text with some other data.
I am unable to get the hint as to how to access the text from the doument main part?
Any help would be appreciable.
Below is my code till now.
private void CreateSampleWordDocument()
{
//string sourceFile = Path.Combine("D:\\GeneralLetter.dot");
//string destinationFile = Path.Combine("D:\\New.doc");
string sourceFile = Path.Combine("D:\\GeneralWelcomeLetter.docx");
string destinationFile = Path.Combine("D:\\New.docx");
try
{
// Create a copy of the template file and open the copy
File.Copy(sourceFile, destinationFile, true);
using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true))
{
// Change the document type to Document
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
//Get the Main Part of the document
MainDocumentPart mainPart = document.MainDocumentPart;
mainPart.Document.Save();
}
}
catch
{
}
}
Now how to find certain text and replace the same? I am unable to get via Link, so some code hint would be appreciable.
In addition to
Flowerking
's answer:When your Word file has textboxes in it, his solution would not work. Because textbox has TextBoxContent element so it will not appear at foreach loop of
Run
s.But when writing
it will loop all the texts in document(whether it is in textbox or not) so it will replace the texts.
Note that if the text is split between Runs or Textboxes, this also won't work. You need a better solution for those cases.
Maybe this solution is easier:
1. a
StreamReader
reads all the text,2. using a
Regex
you case-insensitively replace the new text instead of the old tex3. a
StreamWriter
writes again the modified text into the document.Just to give you the idea of how to do it, please try:
Please note the text is case sensitive. The text formatting won't be changed after the replace. Hope this helps you.
Here is a solution that can find and replace tags in an open xml (word) document across text runs (including text boxes)
here is solution from msdn.
Example from there: