一、使用C#创建Word文档
在常见的信息管理系统中,经常涉及文件的收发、数据的整理及报表功能。除了使用应用程序本身进行显示、处理之外,还必须考虑到企业原有的办公系统。由于大部分企业仍然以使用Word进行字处理为主,一般需要添加进行Word文档输出的功能。本部分介绍如何使用C#创建Word文档的方法。
创建Word文档所使用的主要方法是通过微软公司提供的Microsoft Word X Object Library,其中X为版本号。Word 2007对应12.0,Word2003对应11.0.通过在项目中添加该组件,即可使用微软公司提供的方法创建相应版本的Word文档。
实例介绍创建Word文档的基本知识,演示如何创建Word2003版本的Word文档和Word2007版本的Word文档。
添加引用,引用的库位于"COM"选项卡下,名称为Microsoft Word 12.0 Object Library。其中12.0是版本号,考虑到Microsoft Office 2007版本系列的软件能够比较方便地使用Microsoft Office 2003版本系列创建的文档,本节首先使用Microsoft Word 11.0 Object Library创建一个Word 2003文档。添加后"解决方案资源管理器"面板的引用项中自动多出了三个引用,分别为Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE。
using MSWord=Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
class program
{
static void Main(string[ ] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path =@"C:\MyWord.doc"; //路径
wordApp=new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if(File.Exists((string)path))
{
File.Delete((string)path);
}
由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing =Missing.Value;
wordDoc =wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
//WdSaveFormat为Word文档的保存格式
object format=MSWord.WdSaveFormat.wdFormatDocument;
//将wordDoc文档对象的内容保存为DOC文档
wordDoc.SaveAs(ref path,ref format,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
//关闭wordDoc文档对象
wordDoc.Close(ref Nothing,ref Nothing,ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing,ref Nothing,ref Nothing);
Console.WriteLine(path + "创建完毕!“);
}
}
运行程序,可见已成功创建了一个名为MyWord.doc的word文档,是word2003默认的文档格式,大小约22KB。
下面介绍如何创建一个word2007默认文档格式的word文档,在Microsoft.Office.Interop.Word命名空间下有一个枚举名为WdSaveFormat,设定了可用于保存的形式,对应于Word保存格式,但枚举更为详细。
添加对Microsoft Word 12.0 Object Library的引用,并在Program.cs中添加如下引用:
using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
修改Program.cs文件代码
path=@"C:\MyWord.docx";
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
其余不变,运行程序,成功创建了一个名为MyWord.docx的Word文档,是word2007默认的文档格式,大小约11KB。