C#的office文档操作(2)

来源:互联网 发布:詹姆斯2016为止总数据 编辑:程序博客网 时间:2024/05/16 12:41
4.目的说明
在Microsoft.Office.Interop.Word命名空间下有一个枚举名为WdSaveFormat,设定了可用于保存的形式,如图8.5所示。对应于如图8.6所示的Word保存格式。
      
     图8.5 WdSaveFormat枚举                          图8.6 保存格式
可以看到,WdSaveFormat枚举中定义的格式更为详细,下面介绍如何创建一个Microsoft Word 2007格式的文档。
5.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordXDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用(同之前的步骤,不再详述)。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
    static void Main(string[] args)
    {
        object path;                          //文件路径变量
        string strContent;                    //文本内容变量
        MSWord.Application wordApp;               //Word应用程序变量
        MSWord.Document wordDoc;               //Word文档变量
       
        path = @"C:/MyWord.docx";             //路径
        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);
        //strContent = "你好!/n";
        //wordDoc.Paragraphs.Last.Range.Text = strContent;
        //strContent = "Hello World";
        //wordDoc.Paragraphs.Last.Range.Text = strContent;
         //WdSaveFormat为Word 2007文档的保存格式
        object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
        //将wordDoc文档对象的内容保存为DOCX文档
        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 + " 创建完毕!");
    }
}
6.运行结果
运行程序,结果如图8.7所示。
图8.7 运行结果
打开C盘根目录,如图8.8所示。
图8.8 创建成功
可以看到,已经成功地创建了一个名为MyWord.docx的Word文档。该文档是Microsoft Word 2007默认的文档格式,大小约为11KB。