Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenXML replace text in all document

I have the piece of code below. I'd like replace the text "Text1" by "NewText", that's work. But when I place the text "Text1" in a table that's not work anymore for the "Text1" inside the table.

I'd like make this replacement in the all document.

using (WordprocessingDocument doc = WordprocessingDocument.Open(String.Format("c:\\temp\\filename.docx"), true))
{
    var body = doc.MainDocumentPart.Document.Body;

    foreach (var para in body.Elements<Paragraph>())
    {
        foreach (var run in para.Elements<Run>())
        {
            foreach (var text in run.Elements<Text>())
            {
                if (text.Text.Contains("##Text1##"))
                    text.Text = text.Text.Replace("##Text1##", "NewText");
            }
        }
    }
}
like image 207
Kris-I Avatar asked Sep 30 '13 12:09

Kris-I


2 Answers

Maybe this solution is easier

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
 string docText = null;
 //1. Copy all the file into a string
 using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
     docText = sr.ReadToEnd();

 //2. Use regular expression to replace all text
 Regex regexText = new Regex(find);
 docText = regexText.Replace(docText, replace);

 //3. Write the changed string into the file again
 using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
      sw.Write(docText);
like image 72
Emanuele Greco Avatar answered Oct 23 '22 23:10

Emanuele Greco


Your code does not work because the table element (w:tbl) is not contained in a paragraph element (w:p). See the following MSDN article for more information.

The Text class (serialized as w:t) usually represents literal text within a Run element in a word document. So you could simply search for all w:t elements (Text class) and replace your tag if the text element (w:t) contains your tag:

using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true))
{
  var body = doc.MainDocumentPart.Document.Body;

  foreach (var text in body.Descendants<Text>())
  {
    if (text.Text.Contains("##Text1##"))
    {
      text.Text = text.Text.Replace("##Text1##", "NewText");
    }
  }
}
like image 39
Hans Avatar answered Oct 23 '22 22:10

Hans