【问题标题】:Open XML SDK: opening a Word template and saving to a different file-name打开 XML SDK:打开 Word 模板并保存到不同的文件名
【发布时间】:2011-03-20 00:32:44
【问题描述】:

这是一件非常简单的事情,我找不到合适的技术。我想要的是打开一个 .dotx 模板,进行一些更改并保存为同名但 .docx 扩展名。我可以保存 WordprocessingDocument,但只能保存到加载它的位置。我尝试使用 WordprocessingDocument 手动构建一个新文档并进行了更改,但到目前为止没有任何效果,我尝试了 MainDocumentPart.Document.WriteTo(XmlWriter.Create(targetPath)); 并得到了一个空文件。

这里的正确方法是什么?就 SDK 而言,.dotx 文件是特殊文件还是只是另一个文件 - 我应该简单地将模板复制到目标位置,然后打开 that 并进行更改并保存吗?如果我的应用程序同时从两个客户端调用,我确实有些担心,它是否可以打开同一个 .dotx 文件两次……在这种情况下,无论如何创建副本都是明智的……但出于我自己的好奇心,我仍然想要知道如何进行“另存为”。

【问题讨论】:

    标签: openxml-sdk


    【解决方案1】:

    虽然 M_R_H 的答案是正确的,但还有一种更快、更少 IO 密集型的方法:

    1. 将模板或文档读入MemoryStream
    2. 在 using 语句中:
      • MemoryStream上打开模板或文档。
      • 如果您打开了一个模板 (.dotx) 并希望将其存储为文档 (.docx),则必须将文档类型更改为 WordprocessingDocumentType.Document。否则,当您尝试打开文档时,Word 会报错。
      • 处理您的文档。
    3. MemoryStream 的内容写入文件。

    第一步,我们可以使用下面的方法,将文件读入MemoryStream

    public static MemoryStream ReadAllBytesToMemoryStream(string path)
    {
        byte[] buffer = File.ReadAllBytes(path);
        var destStream = new MemoryStream(buffer.Length);
        destStream.Write(buffer, 0, buffer.Length);
        destStream.Seek(0, SeekOrigin.Begin);
        return destStream;
    }
    

    然后,我们可以通过以下方式使用它(尽可能多地复制 M_R_H 的代码):

    // Step #1 (note the using declaration)
    using MemoryStream stream = ReadAllBytesToMemoryStream(@"\path\to\template.dotx");
    
    // Step #2
    using (WordprocessingDocument newdoc = WordprocessingDocument.Open(stream, true)
    {
        // You must do the following to turn a template into a document.
        newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
    
        // Manipulate document (completely in memory now) ...
    }
    
    // Step #3
    File.WriteAllBytes(@"\path\to\template.docx", stream.GetBuffer());
    

    请参阅此post,了解克隆(或复制)Word 文档或模板的方法的比较。

    【讨论】:

      【解决方案2】:

      我建议只使用 File.IO 将 dotx 文件复制到 docx 文件并在那里进行更改,如果这适用于您的情况。您还必须调用一个 ChangeDocumentType 函数来防止新的 docx 文件中出现错误。

                  File.Copy(@"\path\to\template.dotx", @"\path\to\template.docx");
      
                  using(WordprocessingDocument newdoc = WordprocessingDocument.Open(@"\path\to\template.docx", true))
                  {
                      newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
                      //manipulate document....
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-30
        • 1970-01-01
        相关资源
        最近更新 更多