【问题标题】:Word 2010 Interop: Change the name of the default documentWord 2010 互操作:更改默认文档的名称
【发布时间】:2013-01-17 15:08:30
【问题描述】:

当从我的应用程序启动 Word 文档时,我需要能够将默认文档的名称从 Document1 更改为 Report。问题是 Document 对象中的 name 属性是只读的。关于我可以在启动时调用的更改名称的方法有什么想法吗?

【问题讨论】:

  • 有趣.. 我自己验证了这一点。我猜这类似于在 GUI 中创建一个新文档,并且在保存之前它具有默认名称(Document1、Document2、...等)。我猜想解决这个问题的最好方法是先以编程方式保存文档,然后打开它。

标签: c# interop


【解决方案1】:

您可能对这段 sn-p 代码感兴趣:

    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

    object missing = System.Reflection.Missing.Value;
    object fileName = "Report";
    object isReadOnly = false;
    object isVisible = true;

    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref isVisible);

    doc.SaveAs2(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref isReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);          
    wordApp.Visible = true;

这将弹出一个您指定的名为“报告”的新 Word 文档。请注意,这使用了我在评论中提到的概念,即它首先使用新名称保存文件,然后打开它。在这种情况下,默认位置可能是您用户的“文档”文件夹,但您可以根据需要指定路径。

不要忘记根据需要关闭和释放 COM 对象“doc”和“wordApp”。有时 GC 不会适当地清理所有内容,尤其是在应用程序意外关闭或您在完成后忘记关闭任何应用程序的情况下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2012-08-28
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多