c# - 如何在 MS Word 中以编辑模式启动 template.dot 文件

标签 c# ms-word

我有一个 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/

相关文章:

api - 使用Microsoft Office API在Word文档中将 "Shift-Enter"换行符替换为 "Enter"

c# - 微 Controller ,哪种语言更可取?高层或 assembly

c# - NEST Elasticsearch 中的 Lambda 查询具有过滤器和值数组

c# - Automapper DynamicMap 无法映射匿名类型列表

c# - 根据停靠在其中的 webBrowser 控件中的数据调整自定义用户控件的大小

c# - 通过引入工厂使依赖注入(inject)成为可选?

html - 通过 HTTPS 提供的 Word HTML 动态图像显示为已损坏?

vba - 有更多关于 WordBasic 的 FilePrintSetup 的文档吗?

c# - c#导出数据到word

vba - 使用自定义 UI 功能区部署启用宏的 Word 模板 (.dotm)