【问题标题】:Using OpenXML to replace text in the document使用 OpenXML 替换文档中的文本
【发布时间】:2016-12-23 10:44:01
【问题描述】:

我打开文档并复制到流中。

如何在流之前替换文档中的一些文本?

//wordTemplate  - var with path to my word template
byte[] result = null;
byte[] templateBytes = System.IO.File.ReadAllBytes(wordTemplate);
using (MemoryStream templateStream = new MemoryStream())
{
    templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
    using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
    {
        MainDocumentPart mainPart = doc.MainDocumentPart;

        mainPart.Document.Save();
        templateStream.Position = 0;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            templateStream.CopyTo(memoryStream);
            result = memoryStream.ToArray();
        }
    }
}

【问题讨论】:

  • 目标——打开word文档,修改部分字符串,发送给用户下载
  • 您可以简单地使用Regex 来替换文本。给它一个StreamReader.ReadToEnd()WordprocessingDocument,瞧!注意:您需要重写其中的大部分内容......因为看起来您不是最简单的方法,开始。
  • 谢谢,你能提供一个简短的例子如何做得更好吗?

标签: c# ms-word openxml


【解决方案1】:

为什么不调用 File.ReadAllBytes(),而不是调用 File.ReadAllLines(string) 呢?它为您提供了一系列字符串,然后您可以根据自己的喜好进行搜索和替换。

【讨论】:

  • 我打开docx格式的文档,ReadAllLines如何帮助我替换Word文档中的字符串?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
相关资源
最近更新 更多