3

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

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

4

2 回答 2

6

如果适合您的情况,我建议仅使用 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....
            }
于 2010-07-28T19:52:11.373 回答
0

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

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

第一步,我们可以使用以下方法,将文件读入 a 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());

有关克隆(或复制)Word 文档或模板的方法的比较,请参阅此帖子。

于 2019-11-28T17:26:01.217 回答