C# 从外部应用程序编写Word文档脚本
我正在尝试自动化一个乏味的过程,目前包括启动Word、从.dot创建新文档、保存文档、运行一个或两个使用VSTO以C编写的插件、再次保存、退出文档和退出Word 我想写一个C#命令行应用程序,用户可以使用一个或两个参数启动(传递通常需要与Word中的对话框交互的所有信息),然后在运行时离开,而不需要进一步交互。。。如果必要和可能,在运行时通过Word抑制任何和所有焦点窃取 有什么简单的方法可以做到这一点吗?下面是一个类似Java的伪代码示例,说明了我的想法:C# 从外部应用程序编写Word文档脚本,c#,ms-word,vsto,office-automation,C#,Ms Word,Vsto,Office Automation,我正在尝试自动化一个乏味的过程,目前包括启动Word、从.dot创建新文档、保存文档、运行一个或两个使用VSTO以C编写的插件、再次保存、退出文档和退出Word 我想写一个C#命令行应用程序,用户可以使用一个或两个参数启动(传递通常需要与Word中的对话框交互的所有信息),然后在运行时离开,而不需要进一步交互。。。如果必要和可能,在运行时通过Word抑制任何和所有焦点窃取 有什么简单的方法可以做到这一点吗?下面是一个类似Java的伪代码示例,说明了我的想法: // magic to non-in
// 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...
假设我在正确的轨道上……
- 我很确定我可以通过搜索找到大部分我需要知道的东西。。。一旦我确定了我需要搜索的内容。我应该寻找什么
- 我想在VisualStudio中创建什么样的项目?一个.NET4.5C#控制台应用程序?Word 2010加载项?其他类型的项目
- 我的程序只能在安装了Word 2010的计算机上运行。不需要与旧版本兼容
- 如果它可以在Vista下运行就好了,但它只需要在Win7下工作
- 我有Visual Studio Ultimate 2012
- 安装Visual Studio和Office
- 使用您选择的.NET framework(推荐4.0或更高版本)创建一个C#console项目
- 添加对Word COM库的引用(Project菜单=>Add reference,COM选项卡,Microsoft Word XX.0对象库--Word 2010是14.0)
- 对于上面添加的引用,将嵌入互操作类型设置设置为false
- 在解决方案资源管理器中展开引用
- 选择Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE
- 右键单击并选择属性,以打开引用的属性面板
- 在属性面板中,将嵌入互操作类型设置为False
- 把代码写下来 下面是一些示例代码
- 以下是您需要做的事情:
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();
}
}
}
有关更多信息,请参见这可能是一个更好的问题。(根据他们的描述:“程序员堆栈交换是一个问答网站,面向对软件开发概念性问题感兴趣的专业程序员。”)