我有一个 template.dot Word 文档,如果我使用 Windows 资源管理器,当我右键单击它时,我可以看到功能“新建、打开、打印等”,其中新建是默认选项。
如果我使用 Process.Start("template.dot"),此函数会创建一个新文档 ("document.doc"),因为默认选择是“新建”。 如何在 MS Word 中打开“template.dot”文件进行编辑(例如,当我从右键单击中选择“打开”功能时)?
最佳答案
您可以使用互操作从这样的 .dot/x 模板开始:
using System;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace EditWordDotSO
{
class Program
{
static void Main(string[] args)
{
var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;
Document doc = null;
try
{
doc = applicationWord.Documents.Add(@"path\to\your\a.dotx");
doc.Activate();
}
catch (COMException ex)
{
Console.Write(ex);
//dispose properly as shown below
}
}
}
}
注意:您需要添加对 Microsoft.Office.Interop.Word
的 COM 引用,以绑定(bind)到您安装的 MS Word。
更新:如@CindyMeister 所述,使用
this.Application.Documents.Add(@"C:\Test\SampleTemplate.dotx");
而不是创建一个 new Document()
。引用:How to: Programmatically Create New Documents
PS:finally { ... }
block 旨在关闭文档并正确处理 COM 对象。 Why use finally ?
这是一个更复杂的方法,灵感来自 this帖子:
finally {
doc.Close(null, null, null);
applicationWord.Quit();
if (doc != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
if (applicationWord != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(applicationWord);
doc = null;
applicationWord = null;
GC.Collect(); // final cleanup
}
PPS:也可以这样添加或更改模板:
doc = applicationWord.Documents.Add();
doc.set_AttachedTemplate(@"C:\Test\SampleTemplate.dotx");
doc.UpdateStyles();
关于c# - 如何在 MS Word 中以编辑模式启动 template.dot 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50520085/