【问题标题】:Docx content replacementDocx 内容替换
【发布时间】:2012-05-17 14:23:17
【问题描述】:
using (WordprocessingDocument wordDoc = 
       WordprocessingDocument.Open(document, true))
{
    string docText = null;
    using (StreamReader sr = 
           new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    Regex regexText = new Regex("@@username@@");
    docText = regexText.Replace(docText, "john thomas ");

    using (StreamWriter sw = 
           new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}

这应该用代码中的名称替换 doctext 上的匹配项。我检查了文档文本,要替换的单词 (@@username@@) 已拆分。有时有 XML 内容之间 @@username@@。有时单词本身格式不正确。

如何替换@@username@@

【问题讨论】:

  • 你为什么不使用文字处理合并功能来为字段提供内容而不是滥用正则表达式?
  • 不是 DOCX 文件格式专家,我真的怀疑您是否可以对 DOCX 文件的内容使用字符串函数。我建议使用 Aspose.Words 或 Spire.

标签: c# replace openxml docx


【解决方案1】:

一个简单的解决方法是将标签放在文本框或表格中(甚至可能带有预先指定的 id)。我不确定文档中是否还有其他表格或文本框,但是抓取表格中的内容或文档中唯一的文本框内的内容真的很容易。

【讨论】:

    【解决方案2】:

    如果你在 Paragraph 对象中有代码,那么你可以做这样的事情(一个糟糕的 Order n^2 解决方案 ....):

    foreach (Paragraph para in wordprocessingDocument.MainDocumentPart.Document.Descendants<Paragraph>()) 
    {
        foreach(Run r in para.Elements<Run>()) 
        {
              if (r.Elements<text>().ElementAt(0).Text.Equals(string_to_search)) 
                  r.Elements<Text>().ElementAt(0).Text = string_to_insert;
        }
    }
    

    另外,请查看 MSDN http://msdn.microsoft.com/en-us/library/office/ff478255.aspx

    【讨论】:

      【解决方案3】:

      您可以更改正则表达式。 (这将包括所有的 XML,但会被替换)

      New Regex("@@.*?username.*?@@")
      

      操作代码是 MSDN 上记录的解决方案: https://msdn.microsoft.com/en-us/library/office/bb508261.aspx

      如果您将多个字段替换为不同的名称,您可以尝试在您的阅读器和作者之间调用此函数:

          Private Function ReplaceMatches(ByVal text As String) As String
              Dim Matches = Regex.Matches(text, "@@.*?@@")
              For Each m As Match In Matches
                  For Each c As Capture In m.Captures
                      If Not String.IsNullOrEmpty(c.Value) Then
                          text = text.Replace(c.Value, "NEW-VALUE")
                      End If
                  Next
              Next
              Return text
          End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多