【问题标题】:Scripting Word doc from external app从外部应用程序编写 Word 文档
【发布时间】:2014-04-03 00:59:03
【问题描述】:

我正在尝试自动化当前涉及启动 Word、从 .dot 创建新文档、保存它、运行一个或两个使用 VSTO 用 C# 编写的插件、再次保存、退出文档,并退出 Word。

我想编写一个 C# 命令行应用程序,用户可以使用一个或两个 args 启动它(传达通常需要与 Word 中的对话框交互的所有信息),然后在运行时离开而无需进一步交互...如有必要和可能,在 Word 运行时抑制所有焦点窃取。

有没有一些简单的方法可以做到这一点?这是我想到的类似 Java 的伪代码示例:

// magic to non-interactively launch Word and expose it as an object
WordHost word = xx; 

// create new Word document based on a specific template that isn't the default one.
WordDocument doc = MSWord.create("z:\path\to\arbitraryTemplate.dot");

// If we can avoid physically saving it at this point and just assign a concrete
// file path, it would be even better because the network is glacially slow.
doc.saveAs("z:\path\to\newDoc.docx");

// someZeroArgPlugin and aTwoArgPlugin are VSTO plugins written with C#
doc.someZeroArgPlugin(); 
doc.aTwoArgPlugin("first", "second");

// done!
doc.save();
doc=null;
word=null; // something like word.unload() first?
// now do more things that don't involve Word directly...

假设我在正确的轨道上......

  • 我很确定我可以通过搜索找到我需要知道的大部分内容...一旦我弄清楚我需要搜索什么。我应该搜索什么?

  • 我想在 Visual Studio 中创建什么样的项目? .net 4.5 C# 控制台应用程序? Word 2010 加载项?其他类型的项目?

可能会或可能不会有所作为的细节:

  • 我的程序只能在安装了 Word 2010 的计算机上运行。无需与旧版本兼容。

  • 如果能在Vista下运行就好了,但是必须在Win7下运行。

  • 我有 Visual Studio Ultimate 2012

【问题讨论】:

  • 这对于programmers.stackexchange.com 来说可能是一个更好的问题。 (根据他们的描述:“Programmers Stack Exchange 是一个问答网站,面向对软件开发的概念性问题感兴趣的专业程序员。”)

标签: c# ms-word vsto office-automation


【解决方案1】:

这是您需要做的:

  1. 已安装 Visual Studio 和 Office。
  2. 使用您选择的 .NET 框架创建一个 C# 控制台项目(推荐 4.0 或更高版本)。
  3. 添加对 Word COM 库的引用(项目菜单 => 添加引用COM选项卡、Microsoft Word XX。 0 对象库 -- Word 2010 14.0)。
  4. 对于上面添加的引用,将 Embed Interop Types 设置为 false
    1. Solution Explorer中展开References
    2. 选择 Microsoft.Office.CoreMicrosoft.Office.Interop.WordVBIDE
    3. 右击并选择Properties以调出Properties面板以供参考。
    4. Properties 面板中,将 Embed Interop Types 设置为 False
  5. 编码。

这里有一些示例代码。

using System;
using Microsoft.Office.Interop.Word;

namespace CSharpConsole
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            var application = new ApplicationClass();
            var document = application.Documents.Add();
            document.SaveAs("D:\test.docx");
            application.Quit();
        }
    }
}

欲了解更多信息,请参阅http://msdn.microsoft.com/en-us/library/office/ff601860(v=office.14).aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多