11

我有一些代码可以打开 Word 2007 (docx) 文档并更新适当的 CustomXmlPart(从而在文档本身中更新内容控件,因为它们映射到 CustomXmlPart),但无法解决如何将其保存为一个新文件。!肯定不会那么难!

我目前的想法是我需要打开模板并将内容复制到一个新的空白文档中 - 一个文件一个文件,当我遇到它时更新 CustomXmlPart。叫我老式的,但这对我来说听起来有点笨拙!

为什么我不能只做一个 WordprocessingDocument.SaveAs(filename); ...?

请告诉我我在这里遗漏了一些简单的东西。

提前致谢

4

4 回答 4

16

您指的是 OpenXml SDK 吗?不幸的是,从 OpenXml SDK 2.0 开始,没有 SaveAs 方法。您需要:

  1. 制作模板文件的临时副本,随意命名。
  2. 对上述文件执行 OpenXml 更改。
  3. myWordDocument.MainDocumentPart.Document.Save()保存适当的部分(即,对主要内容使用 .方法或someHeaderPart.Header.Save()对特定标题使用方法)。
于 2009-08-19T20:10:03.963 回答
1

您可以使用 MemoryStream 来写入更改,而不是在原始文件中。因此,您可以将该 MemoryStream 保存到一个新文件中:

byte[] byteArray = File.ReadAllBytes("c:\\temp\\mytemplate.docx");
using (var stream = new MemoryStream())
{
    stream.Write(byteArray, 0, byteArray.Length);
    using (var wordDoc = WordprocessingDocument.Open(stream, true))
    {
       // Do work here
       // ...
       wordDoc.MainDocumentPart.Document.Save(); // won't update the original file 
    }
    // Save the file with the new name
    stream.Position = 0;
    File.WriteAllBytes("C:\\temp\\newFile.docx", stream.ToArray()); 
}
于 2018-05-29T02:20:04.553 回答
0

实际上,至少在 OpenXml SDK 2.5 中您可以。但是,请注意使用原始文件的副本,因为 XML 中的更改实际上会反映在文件中。在这里,您有我的自定义类的 Load 和 Save 方法(删除一些验证代码后,...):

    public void Load(string pathToDocx)
    {
        _tempFilePath = CloneFileInTemp(pathToDocx);
        _document = WordprocessingDocument.Open(_tempFilePath, true);
        _documentElement = _document.MainDocumentPart.Document;
    }    

    public void Save(string pathToDocx)
    {
        using(FileStream fileStream = new FileStream(pathToDocx, FileMode.Create))
        {
            _document.MainDocumentPart.Document.Save(fileStream);
        }
    }

将“_document”作为WordprocessingDocument实例。

于 2016-03-18T11:57:27.630 回答
0

在 Open XML SDK 2.5 中,当 AutoSave 为 true 时,关闭会保存更改。在这里查看我的答案: https ://stackoverflow.com/a/36335092/3285954

于 2016-03-31T13:53:36.060 回答