概述
某项目需要自动生成Word文档,查找了许多资料,发现还是C#实现起来比较容易,也比较灵活。
环境:
Office 2010
Visual Studio 2010
Win10
网上找了很多教程,首先需要设置引用。
1.右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2.在“添加引用”对话框中,选择“COM”>“Microsoft Word 15.0 Object Library”,点击“确定”按钮(这个版本号和本机安装的Word版本有关,2010是15.0)
3.相同操作打开“添加引用”对话框中,选择“浏览”项,查找到”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”按钮。
整个类的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace DocCreator
{
class CreateDoc
{
private Microsoft.Office.Interop.Word.Application wordApp = null;
private Document wordDoc = null;
public Application Application
{
get
{
return wordApp;
}
set
{
wordApp = value;
}
}
public Document Document
{
get
{
return wordDoc;
}
set
{
wordDoc= value;
}
}
//通过模板创建新文档
public void CreateNewDocument(string filePath)
{
killWinWordProcess();
wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.Visible =false;
object missing = System.Reflection.Missing.Value;
object templateName = filePath;
wordDoc = wordApp.Documents.Open(ref templateName,ref missing,
ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,
ref missing,ref missing,ref missing,ref missing,ref missing);
}
//保存新文件
public void SaveDocument(string filePath)
{
object fileName = filePath;
obj