VSTO中的完整word文档副本



我试图将word文档复制到另一个而不关闭目标文档。所以,我这样做:

temp_doc_.Content.Copy();
target_doc_.Content.Paste();
temp_doc_.Close(SaveChanges: false);

然而,这不能复制一些功能,如页边距,页眉高度,…等。它只复制部分段落。有谁知道怎么做一个完整的副本,这样他们在所有的东西上都是一样的吗?

您只是复制文档的主体,而不是使用document。SaveAs2…

https://learn.microsoft.com/en - us/dotnet/api/microsoft.office.tools.word.document.saveas2?view=vsto - 2017

我不能100%确定这将处理页边距,但它将处理页眉和页脚。

Word.Document tempDoc = wordApp.Documents.Open('tempdoc.docx');
Word.Document targetDoc = wordApp.Documents.Open('targetdoc.docx');
tempDoc.Activate();
tempDoc.Application.Selection.WholeStory();
tempDoc.Application.Selection.Copy();
targetDoc.Activate();
targetDoc.Application.Selection.WholeStory();
targetDoc.Application.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);

您可以在不关闭文档的情况下复制打开的文档,并且不会影响文档的"已保存"状态。

filePath可以在temp文件夹或类似文件夹中。

sourceDocument必须是Microsoft.Word.Document实例。

VB

Dim persistFile = CType(sourceDocument, Runtime.InteropServices.ComTypes.IPersistFile)
persistFile.Save(filePath, False)

c#

var persistFile = (Runtime.InteropServices.ComTypes.IPersistFile)sourceDocument;
persistFile.Save(filePath, False);

然后打开复制的文件,你就得到了整个文档的完整克隆。

最新更新