虽然 M_R_H 的回答是正确的,但有一种更快、更少 IO 密集型的方法:
- 将模板或文档读入
MemoryStream
.
- 在 using 语句中:
- 打开 上的模板或文档
MemoryStream
。
- 如果您打开了模板 (.dotx) 并且想要将其存储为文档 (.docx),则必须将文档类型更改为
WordprocessingDocumentType.Document
. 否则,当您尝试打开文档时,Word 会报错。
- 操作您的文档。
- 将 的内容写入
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 文档或模板的方法的比较,请参阅此帖子。