C#的office文档操作

来源:互联网 发布:薛之谦淘宝下线 编辑:程序博客网 时间:2024/05/02 01:13

http://blog.csdn.net/wudi626/article/details/2337857#comments


Microsoft Office是微软公司推出的办公应用程序,主要包括Microsoft Word,Microsoft Excel、Microsoft Outlook和Microsoft Access等应用程序。提供了诸如字处理、表格处理、邮件处理和数据库等功能。目前被广泛使用的版本是Microsoft Office 2003和Microsoft Office 2007。作为微软公司推出的重量级编程语言,C#中提供了对大部分Office文件和应用的支持。本章主要介绍如何使用C#操作各类Office文件。
8.1  使用C#创建Word文档
在常见的信息管理系统中,经常涉及文件的收发、数据的整理及报表功能。除了使用应用程序本身进行显示、处理之外,还必须考虑到企业原有的办公系统。由于大部分企业仍然以使用Word进行字处理为主,一般需要添加进行Word文档输出的功能。本部分介绍如何使用C#创建Word文档的方法。
创建Word文档所使用的主要方法是通过微软公司提供的Microsoft Word X Object Library,其中X为版本号。Word 2007对应12.0,Word 2003对应11.0。通过在项目中添加该组件,即可使用微软公司提供的方法创建相应版本的Word文档。
1.目的说明
介绍创建Word文档的基本知识,通过实例演示如何创建Word 2003版本的Word文档和Word 2007版本的Word文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordDemo。
(2)添加引用,如图8.1所示。
引用的库位于“COM”选项卡下,名称为Microsoft Word 12.0 Object Library。其中12.0是版本号,对应Microsoft Word 2007。Microsoft Word 2003对应的版本号为11.0。考虑到Microsoft Office 2007版本系列的软件能够比较方便地使用Microsoft Office 2003版本系列创建的文档,本节首先使用Microsoft Word 11.0 Object Library创建一个Word 2003文档。
添加后“解决方案资源管理器”面板的引用项中自动多出了三个引用,如图8.2所示。分别为Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE。
             
               图8.1  添加引用                            图8.2  “解决方案资源管理器”面板
(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.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 + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.3所示。
打开C盘根目录,如图8.4所示。
    
            图8.3  运行结果                             图8.4  创建成功
可以看到,已经成功地创建了一个名为MyWord.doc的Word文档。该文档是Microsoft Word 2003默认的文档格式,大小约为22KB。下面介绍如何使用其创建一个Microsoft Word 2007默认文档格式的Word文档。
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。
8.2  使用C#向Word文档中写入文本
文本是一个Word文档中最简单的元素,通过各种形式的文本与其他元素有机组合才形成了一个完整的Word文档。本节介绍如何使用C#向Word文档中写入文本信息。
在向Word文档中写入文本时,仍然需要使用上节介绍的Microsoft Word X Object Library COM组件。写入文本的方法主要为设置MSWord.Document.Paragraphs.Last.Range.Text属性,通过设置不同的字符串,即可达到写入文本的目的。
1.目的说明
介绍如何向Word文档中写入文本和如何向Word文档中写入多行文本。
2.操作步骤
(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 = "使用C#向Word文档中写入文本/n";
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        strContent = "写入第二行文本";
        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 + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.9所示。
图8.9  运行结果
打开C盘根目录下的MyWord.docx,如图8.10所示。
图8.10  运行结果
8.3  使用C#向Word输出格式化的文本
一个Word文档不可能全部由无格式的普通文本组成,因此在从C#中向Word写入文本信息时经常要输出一些具有特殊字体、颜色的文本。本节介绍如何向Word输出格式化的文本。
Microsoft Word X Object Library COM组件中文本格式的设置主要是由文本所使用的字体决定的。该COM组件中可以直接设置C#中的Font类,使用非常方便。常用的格式属性有颜色、加粗、斜体、下画线等。
1.目的说明
分别介绍以下内容:
— 输出不同字体的文本。
— 输出不同颜色的文本。
— 输出带下画线的文本。
— 输出斜体文本。
— 输出加粗文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateFormatWordDemo。
(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 = "黑体文本黑体文本黑体文本黑体文本黑体文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入加粗文本
        strContent = "加粗文本加粗文本加粗文本加粗文本加粗文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入15号字体文本
        strContent = "15号字体文本15号字体文本15号字体文本15号字体文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Size = 15;
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入斜体文本
        strContent = "斜体文本斜体文本斜体文本斜体文本斜体文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入蓝色文本
        strContent = "蓝色文本蓝色文本蓝色文本蓝色文本蓝色文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入下画线文本
        strContent = "下画线文本下画线文本下画线文本下画线文本下画线文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
        wordDoc.Paragraphs.Last.Range.Text = strContent;
        //写入红色下画线文本
        strContent = "红色下画线文本红色下画线文本红色下画线文本红色下画线文本/n";
        wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
        wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
        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 + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.11所示。
打开C盘根目录下的MyWord.docx,如图8.12所示。
  
          图8.11  运行结果                               图8.12  运行结果
8.4  使用C#向Word文档中添加表格
除了简单的文本信息外,Microsoft Word也是一个处理表格的强大工具。许多数据报表也需要通过表格的形式在Word中体现。本节将介绍如何使用C#在Word中创建一个表格。
表格是由Microsoft Word X Object Library中的MSWord.Table定义的,通过在Word文档中的Tables集合中添加一个Table对象,即可在Word文档中创建一个表格。该表格的行数和列数等属性都可以在Tables的Add方法中定义,表格的内容可由Cell属性访问。
1.目的说明
介绍如何向Word文档中输出表格和如何向Word文档中的表格填充文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateTableDemo。
(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);
        //定义一个Word中的表格对象
        MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 5, 5, ref Nothing, ref Nothing);
            //默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
            table.Borders.Enable = 1;
            //使用两层循环填充表格的内容
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    table.Cell(i,j).Range.Text = "第"+ i +"行,第"+ j +"列";
                }
            }
            //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 + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.13所示。
打开C盘根目录下的MyWord.docx,如图8.14所示。
  
           图8.13  运行结果                             图8.14  运行结果
8.5  使用C#向Word文档中插入图片
要想创建一个完整美观的Word文档,图片是必不可少的。本节将要介绍的内容就是如何从C#中向Word文档中写入一个图片文件。
在COM组件Microsoft Word X Object Library中,图片是由MSWord.Document. InlineShapes.AddPicture负责添加的,而没有单独表示图片的对象。只需用AddPicture方法给出图片的物理地址及一些简单的属性即可向Word文档中添加图片。
1.目的说明
本实例介绍的知识点为如何向Word文档中输出图片。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePicDemo。
(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);
        //图片文件的路径
        string filename = @"C:/BackgroundImage.jpg";
        //要向Word文档中插入图片的位置
        Object range = wordDoc.Paragraphs.Last.Range;
        //定义该插入的图片是否为外部链接
        Object linkToFile = false;                //默认
        //定义要插入的图片是否随Word文档一起保存
        Object saveWithDocument = true;               //默认
        //使用InlineShapes.AddPicture方法插入图片
        wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
        //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 + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.15所示。
图8.15  运行结果
打开C盘根目录下的MyWord.docx,如图8.16所示。
图8.16  运行结果
8.6  使用C#创建Excel文档
Microsoft Excel是Microsoft Office的一个组件,是功能强大的电子表格处理软件,它与文本处理软件的差别在于它能够运算复杂的公式,并且有条理地显示结果。Microsoft Excel是除了Microsoft Word之外最常用的办公软件之一,本节将介绍如何使用C#创建Excel文档。
与在C#中添加Word文档的方法类似,添加Excel文档时需要为项目添加对Microsoft ExcelX Object Library的引用,其中的X对应为版本号。Excel 2007对应12.0。在Microsoft ExcelX Object Library中,一个Excel文档由MSExcel.Workbook表示。
1.目的说明
本实例介绍的知识点为如何创建Excel文档和如何使用不同格式保存创建的Excel文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordDemo。
(2)添加引用,如图8.17所示。
引用的库位于“COM”选项卡下,名称为Microsoft Excel 12.0 Object Library。其中12.0是版本号,对应Microsoft Excel 2007。Microsoft Excel 2003对应的版本号为11.0。本节使用Microsoft Excel 12.0 Object Library。
添加后在“解决方案资源管理器”面板的引用项中自动多出了三个引用,如图8.18所示。分别为Microsoft.Office.Core、Microsoft.Office.Interop. Excel和VBIDE。
         
                  图8.17  添加引用                      图8.18  “解决方案资源管理器”面板
(3)在“Program.cs”文件中添加如下引用。
using MSExcel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
    static void Main(string[] args)
    {
        object path;                               //文件路径变量
        MSExcel.Application excelApp;              //Excel应用程序变量
        MSExcel.Workbook excelDoc;                     //Excel文档变量
       
        path = @"C:/MyExcel.xlsx";                     //路径
        excelApp = new MSExcel.ApplicationClass();     //初始化
        //如果已存在,则删除
        if (File.Exists((string)path))
        {
            File.Delete((string)path);
        }
        //由于使用的是COM库,因此有许多变量需要用Nothing代替
        Object Nothing = Missing.Value;
        excelDoc = excelApp.Workbooks.Add(Nothing);
        //WdSaveFormat为Excel文档的保存格式
        object format = MSExcel.XlFileFormat.xlWorkbookDefault;
        //将excelDoc文档对象的内容保存为XLSX文档
        excelDoc.SaveAs(path, Nothing, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
        //关闭excelDoc文档对象
        excelDoc.Close(Nothing, Nothing, Nothing);
        //关闭excelApp组件对象
        excelApp.Quit();
        Console.WriteLine(path + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.19所示。
打开C盘根目录,如图8.20所示。
      
         图8.19  运行结果                              图8.20  创建成功
可以看到,已经成功地创建了一个名为MyExcel.xlsx的Excel文档。该文档是Microsoft Excel 2007默认的文档格式,大小约为8KB。下面介绍如何使用其创建一个Microsoft Excel 2007中可以识别的其他格式的Excel文档。
在Microsoft.Office.Interop.Excel命名空间下有一个枚举名为XlFileFormat,设定了可用于保存的形式,如图8.21所示,对应于如图8.22所示的Excel保存格式。
可以看到,XlFileFormat枚举中定义的格式更为详细,下面介绍如何创建一个CSV格式的文档。
4.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateCSVDemo。
(2)添加对Microsoft Excel 12.0 Object Library的引用(同之前的步骤,不再详述)。
(3)在“Program.cs”文件中添加如下引用。
using MSExcel = Microsoft.Office.Interop. Excel;
using System.IO;
using System.Reflection;
        
图8.21  XlFileFormat枚举                            图8.22  保存格式
(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 + " 创建完毕!");
    }
}
5.运行结果
运行程序,结果如图8.23所示。
单击“是”按钮,如图8.24所示。
                
               图8.23  运行提示                                 图8.24  运行结果
打开C盘根目录,如图8.25所示。
可以看到,已经成功创建了一个名为MyExcel.csv的CSV文档。该文档是Microsoft Excel 2007支持的文档格式,大小约为8KB。
图8.25  创建成功
8.7  使用C#向Excel文档中写入数据
Microsoft Excel的强大功能就在于其数据处理功能,用户可以通过其方便的操作和强大的公式和图表处理现有的数据。本节介绍如何使用C#向Excel文档中写入数据。
在Excel文档中,数据是有明确的标识的,一般由其行名称和列名称进行标识。在C#中向Excel文档写入数据时,Microsoft ExcelX Object Library也提供了这种支持。只需明确地给出所需添加的位置,即可向Excel文档的指定位置添加数据。
1.目的说明
本实例介绍的知识点为如何向Excel文档中输出数据和如何设定输出数据的位置。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为WriteExcelDemo。
(2)添加对Microsoft Excel 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSExcel = Microsoft.Office.Interop. Excel;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
    static void Main(string[] args)
    {
        object path;                           //文件路径变量
        MSExcel.Application excelApp;              //Excel应用程序变量
        MSExcel.Workbook excelDoc;                     //Excel文档变量
        
        path = @"C:/MyExcel.xlsx";                     //路径
        excelApp = new MSExcel.ApplicationClass();     //初始化
        //如果已存在,则删除
        if (File.Exists((string)path))
        {
            File.Delete((string)path);
        }
        //由于使用的是COM库,因此有许多变量需要用Nothing代替
        Object Nothing = Missing.Value;
        excelDoc = excelApp.Workbooks.Add(Nothing);
        //使用第一个工作表作为插入数据的工作表
        MSExcel.Worksheet ws = (MSExcel.Worksheet)excelDoc.Sheets[1];
        //声明一个MSExcel.Range 类型的变量r
        MSExcel.Range r;
        //获得A1处的表格,并赋值
        r = ws.get_Range("A1", "A1");
        r.Value2 = "数据1";
        //获得A2处的表格,并赋值
        r = ws.get_Range("A2", "A2");
        r.Value2 = "5.7";
        //WdSaveFormat为Excel文档的保存格式
        object format = MSExcel.XlFileFormat.xlWorkbookDefault;
        //将excelDoc文档对象的内容保存为XLSX文档
        excelDoc.SaveAs(path, format, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
        //关闭excelDoc文档对象
        excelDoc.Close(Nothing, Nothing, Nothing);
        //关闭excelApp组件对象
        excelApp.Quit();
        Console.WriteLine(path + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.26所示。
图8.26  运行结果
打开C盘根目录下的MyExcel.xlsx文件,如图8.27所示。
图8.27  创建成功
8.8  使用C#在Excel文档中创建图表
图表功能是Excel中一项非常强大的功能,能将表格中的数据生成直观的图表,便于观看。本节介绍如何使用C#在Excel文档中创建图表。
若要在C#中向Excel文档添加图表,首先需要添加图表的支持数据。图表的形成是以数据为基础的,因此首先需要使用上节介绍的方法添加部分数据。然后根据数据向MSExcel.Workbook.Charts集合中添加图表,使用的是MSExcel.Workbook.Charts.Add方法。图表的样式由MSExcel.XlChartType枚举指定,名称由ChartTitle.Text属性指定。
1.目的说明
本实例主要介绍以下内容:
— 如何向Excel文档中输出多个数据。
— 如何向Excel文档中输出图表。
— 如何设定图表的名称。
— 如何设定图表的样式。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为WriteExcelDemo。
(2)添加对Microsoft Excel 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSExcel = Microsoft.Office.Interop. Excel;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
    static void Main(string[] args)
    {
        object path;                               //文件路径变量
        MSExcel.Application excelApp;              //Excel应用程序变量
        MSExcel.Workbook excelDoc;                     //Excel文档变量
       
        path = @"C:/MyExcel.xlsx";                     //路径
        excelApp = new MSExcel.ApplicationClass();     //初始化
        //如果已存在,则删除
        if (File.Exists((string)path))
        {
            File.Delete((string)path);
        }
        //由于使用的是COM库,因此有许多变量需要用Nothing代替
        Object Nothing = Missing.Value;
        excelDoc = excelApp.Workbooks.Add(Nothing);
        //使用第一个工作表作为插入数据的工作表
        MSExcel.Worksheet ws = (MSExcel.Worksheet)excelDoc.Sheets[1];
        //声明一个MSExcel.Range 类型的变量r
        MSExcel.Range r;
        //获得A1处的表格,并赋值
        r = ws.get_Range("A1", "A1");
        r.Value2 = "3";
        //获得A2处的表格,并赋值
        r = ws.get_Range("A2", "A2");
        r.Value2 = "5.7";
        //获得A3处的表格,并赋值
        r = ws.get_Range("A3", "A3");
        r.Value2 = "4.8";
        //获得A4处的表格,并赋值
        r = ws.get_Range("A4", "A4");
        r.Value2 = "9.2";
        //获得A5处的表格,并赋值
        r = ws.get_Range("A5", "A5");
        r.Value2 = "6.4";
        excelDoc.Charts.Add(Nothing, Nothing, Nothing, Nothing);
        excelDoc.ActiveChart.ChartType = MSExcel.XlChartType.xlColumnClustered;
        excelDoc.ActiveChart.SetSourceData(ws.get_Range("A1", "A5"), MSExcel.XlRowCol.xlColumns);
        excelDoc.ActiveChart.Location(MSExcel.XlChartLocation.xlLocationAsObject, "sheet1");
        excelDoc.ActiveChart.HasTitle = true;
        excelDoc.ActiveChart.ChartTitle.Text = "创建图表";
        excelDoc.ActiveChart.HasDataTable = false;
        //WdSaveFormat为Excel文档的保存格式
        object format = MSExcel.XlFileFormat.xlWorkbookDefault;
        //将excelDoc文档对象的内容保存为XLSX文档
        excelDoc.SaveAs(path, format, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
        //关闭excelDoc文档对象
        excelDoc.Close(Nothing, Nothing, Nothing);
        //关闭excelApp组件对象
        excelApp.Quit();
        Console.WriteLine(path + " 创建完毕!");
    }
}
3.运行结果
运行程序,结果如图8.28所示。
图8.28  运行结果
打开C盘根目录下的MyExcel.xlsx文件,如图8.29所示。
图8.29  创建成功
8.9  使用C#创建PowerPoint文档
Microsoft PowerPoint是Microsoft Office的一个组件,是一款功能强大的演示文稿处理软件,它与其他软件的差别在于其能够创建精美的演示性文档,并且有条理地显示结果。Microsoft PowerPoint是除了Microsoft Word和Microsoft Excel之外最常用的办公软件之一。本节将介绍如何使用C#创建PowerPoint文档。
与在C#中添加Word、Excel文档的方法类似,添加PowerPoint文档时,需要为项目添加对Microsoft PowerPoint X Object Library的引用,其中的X对应为版本号。PowerPoint 2007对应12.0。在Microsoft PowerPoint X Object Library中,一个PowerPoint文档由MSPowerPoint.Presentations表示。
1.目的说明
本实例介绍的知识点为如何创建PowerPoint文档,以及如何使用不同格式保存创建的PowerPoint文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePptDemo。
(2)添加引用,如图8.30所示。
           
图8.30  添加引用                       图8.31  “解决方案资源管理器”面板
引用的库位于“COM”选项卡下,名称为Microsoft PowerPoint X Object Library。其中X是版本号,12.0对应Microsoft PowerPoint 2007。Microsoft PowerPoint 2003对应的版本号为11.0。本节使用Microsoft Excel 11.0 Object Library。
添加后“解决方案资源管理器”面板的引用项中自动多出了三个引用,如图8.31所示。分别为Microsoft.Office.Core、Microsoft.Office.Interop. PowerPoint和VBIDE。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
namespace CreatePptDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path;                        //文件路径变量
            PPT.Application pptApp;                 //Excel应用程序变量
            PPT.Presentation pptDoc;                //Excel文档变量
            path = @"C:/MyPPT.ppt";                 //路径
            pptApp = new PPT.ApplicationClass();    //初始化
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;
            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;
            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
            //关闭excelDoc文档对象
            pptDoc.Close();
            //关闭excelApp组件对象
            pptApp.Quit();
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadLine();
        }
    }
}
3.运行结果
运行程序,结果如图8.32所示。
打开C盘根目录,如图8.33所示。
        
图8.32  运行结果                            图8.33  创建成功
可以看到,已经成功地创建了一个名为MyPPT.ppt的PowerPoint文档。该文档是Microsoft PowerPoint 2003默认的文档格式,大小约为25KB。下面介绍如何使用其创建一个在Microsoft PowerPoint 2003中可以识别的其他格式的PowerPoint文档。
在Microsoft.Office.Interop.PowerPoint命名空间下有一个枚举名为PpSaveAsFileFormat,设置了可用于保存的形式,如图8.34所示,对应于图8.35所示的保存格式。
   
图8.34  PpSaveAsFileFormat枚举                   图8.35  保存格式
可以看到,PpSaveAsFileFormat枚举中定义的格式更为详细。下面将介绍如何创建一个PPS格式的文档。
1.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePPSDemo。
(2)添加对Microsoft Excel 11.0 Object Library的引用(同之前的步骤,不再详述)。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
namespace CreatePpsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path;                        //文件路径变量
            PPT.Application pptApp;                 //Excel应用程序变量
            PPT.Presentation pptDoc;                //Excel文档变量
            path = @"C:/MyPPT.pps";                 //路径
            pptApp = new PPT.ApplicationClass();    //初始化
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;
            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsShow;
            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
            //关闭excelDoc文档对象
            pptDoc.Close();
            //关闭excelApp组件对象
            pptApp.Quit();
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadLine();
        }
    }
}
2.运行结果
运行程序,结果如图8.36所示。
打开C盘根目录,如图8.37所示。
        
图8.36  运行结果                             图8.37  创建成功
可以看到,已经成功地创建了一个名为MyPPT.pps的PPS文档。该文档是Microsoft PowerPoint 2003支持的文档格式,大小约为25KB。
8.10  使用C#向PowerPoint文档中写入数据
Microsoft PowerPoint的强大就在于其演示功能,用户可以通过其方便的操作和易用的特性形成一个漂亮的演示文档。本节将介绍如何使用C#向PowerPoint文档中写入数据。
1.目的说明
本实例介绍的知识点为如何向PowerPoint文档中输出数据,以及如何设置输出数据的位置。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为WritePPTDemo。
(2)添加对Microsoft PowerPoint 11.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
namespace WritePptDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path;                        //文件路径变量
            PPT.Application pptApp;                 //Excel应用程序变量
            PPT.Presentation pptDoc;                //Excel文档变量
            path = @"C:/MyPPT.ppt";                 //路径
            pptApp = new PPT.ApplicationClass();    //初始化
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;
            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;
            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
            //关闭excelDoc文档对象
            pptDoc.Close();
            //关闭excelApp组件对象
            pptApp.Quit();
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadLine();
        }
    }
}
3.运行结果
运行程序,结果如图8.38所示。
 
图8.38  运行结果   
打开C盘根目录下的MyPPT.ppt文件,如图8.39所示。
图8.39  创建成功
从结果中可以看到,已经为Powerpoint文档创建了一个页面。下面将介绍如何向该空白页面插入部分文本。
直接修改“Program.cs”文件的代码如下。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Reflection;
namespace WritePptDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path;                        //文件路径变量
            PPT.Application pptApp;                 //Excel应用程序变量
            PPT.Presentation pptDoc;                //Excel文档变量
            path = @"C:/MyPPT.ppt";                 //路径
            pptApp = new PPT.ApplicationClass();    //初始化
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;
            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);
            string text = "示例文本";
            foreach (PPT.Slide slide in pptDoc.Slides)
            {
                foreach (PPT.Shape shape in slide.Shapes)
                {
                    shape.TextFrame.TextRange.InsertAfter(text);
                }
            }
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;
            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
            //关闭excelDoc文档对象
            pptDoc.Close();
            //关闭excelApp组件对象
            pptApp.Quit();
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadLine();
        }
    }
}
运行程序,结果如图8.40所示。
图8.40  运行结果 
打开C盘根目录下的MyPPT.ppt文件,如图8.41所示。
图8.41  创建成功
从结果中可以看到,Powerpoint文档中已经插入了部分文本,形成了一个简单的演示文档。
8.11  使用C#在PowerPoint文档中添加图片
图片演示功能是PowerPoint中另一项非常易用的功能。一般而言,一个完整的PowerPoint文档中不会只包含文字,通常还会包含一些图片。
1.目的说明
本实例主要介绍如何向PowerPoint文档中输出图片。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为WritePptPicDemo。
(2)添加对Microsoft PowerPoint 11.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
namespace WritePptPicDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path;                        //文件路径变量
            PPT.Application pptApp;                 //Excel应用程序变量
            PPT.Presentation pptDoc;                //Excel文档变量
            path = @"C:/MyPPT.ppt";                 //路径
            pptApp = new PPT.ApplicationClass();    //初始化
            //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }
            //由于使用的是COM库,因此有许多变量需要用Nothing代替
            Object Nothing = Missing.Value;
            pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoc.Slides.Add(1, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutBlank);
            string pic = @"c:/windows/winnt.bmp";
            foreach (PPT.Slide slide in pptDoc.Slides)
            {
                slide.Shapes.AddPicture(pic, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 150, 300, 200);
            }
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;
            //将excelDoc文档对象的内容保存为XLSX文档
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
            //关闭excelDoc文档对象
            pptDoc.Close();
            //关闭excelApp组件对象
            pptApp.Quit();
            Console.WriteLine(path + " 创建完毕!");
            Console.ReadLine();
        }
    }
}
3.运行结果
运行程序,结果如图8.42所示。
图8.42  运行结果
打开C盘根目录下的MyPPT.ppt文件,如图8.43所示。
从结果中可以看到,PowerPoint文档中已经插入了一张图片,形成了一个简单的演示文档。
图8.43  创建成功
8.12  创建PDF文档
PDF文档格式是网络中一种重要的文档格式,在某些领域应用比Office系列文档格式还要广泛。因此在应用程序的需求中经常需要对PDF格式的文档进行创建、修改和读取等操作。本节将介绍PDF文档的创建。
1.目的说明
本实例主要介绍如何创建PDF文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePDFDemo。
(2)添加对iTextSharp的引用,iTextSharp是一个开源的PDF操作类库。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace CreatePDFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("创建一个PDF文档");
            // 创建一个Document对象
            Document document = new Document();
            try
            {
                // 创建文档
                PdfWriter.GetInstance(document, new FileStream(@"c:/Create.pdf", FileMode.Create));
                // 打开文档
                document.Open();
                document.Add(new Paragraph("PDF"));
                document.Add(new Paragraph("PDF"));
                document.Add(new Paragraph("PDF"));
                document.Add(new Paragraph("PDF"));
                document.Add(new Paragraph("PDF"));
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.44所示。
 
图8.44  运行结果
可以使用Adobe Reader来查看在C盘根目录下生成的PDF文档,如图8.45所示。
图8.45  运行结果
8.13  设置PDF文档页面大小
PDF文档是可以设置页面大小的,之前创建的PDF文档是默认大小的。本节将介绍在创建PDF文档时,进行文档页面大小的设置。
1.目的说明
本实例主要介绍如何设置PDF文档页面的大小。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为SetPdfSizeDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace SetPdfSizeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("设置页面大小");
            // 设置页面
            Rectangle pageSize = new Rectangle(320, 240);
            pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
            Document document = new Document(pageSize);
            try
            {
                //创建文档
                PdfWriter.GetInstance(document, new FileStream(@"C:/Size.pdf", FileMode.Create));
                // 打开文档
                document.Open();
                // 添加文档内容
                for (int i = 0; i < 5; i++)
                {
                    document.Add(new Paragraph("PDF ,PDF ,PDF ,PDF ,PDF"));
                }
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.46所示。
 
图8.46  运行结果
打开创建的PDF文档,如图8.47所示。
图8.47  运行结果
8.14  设置PDF文档边界
同Office中的Word文档一样,PDF文档也可以设置文档的格式,比如文档边界等。本节将介绍如何在C#中生成PDF文档的时候设置PDF文档的边界。
1.目的说明
本实例主要介绍如何设置PDF文档边界。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为SetPdfMarginDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using System.Diagnostics;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
            Console.WriteLine("设置边界");
            // 声明文档变量
            Document document = new Document(PageSize.A5, 36, 72, 108, 180);
            try
            {
                // 创建PDF文档
                PdfWriter.GetInstance(document, new FileStream(@"c:/Margin.pdf", FileMode.Create));
                // 打开文档
                document.Open();
                // 添加部分内容
                Paragraph paragraph = new Paragraph();
                paragraph.Alignment = Element.ALIGN_JUSTIFIED;
                for (int i = 0; i < 20; i++)
                {
                    paragraph.Add("PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF, PDF");
                }
                document.Add(paragraph);
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.48所示。
打开创建的PDF文档,如图8.49所示。
   
图8.48  运行结果                           图8.49  运行结果
8.15  设置PDF文档信息
PDF文档中可以包含一些与文档内容本身无关的信息,这部分信息可以包括文档的题目和作者名等一些额外的信息,便于对PDF文档进行其他处理。本节将介绍设置PDF文档信息的方法。
1.目的说明
本实例主要介绍如何设置PDF文档信息。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为SetPdfInfoDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace SetPdfInfoDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("设置信息");
            // 声明文档变量
            Document document = new Document();
            try
            {
                // 创建文档
                PdfWriter.GetInstance(document, new FileStream(@"C:/Info.pdf", FileMode.Create));
                // 添加文档信息
                document.AddTitle("PDFInfo");
                document.AddSubject("Demo of PDFInfo");
                document.AddKeywords("Info, PDF, Demo");
                document.AddCreator("SetPdfInfoDemo");
                document.AddAuthor("Z");
                document.Open();
                // 添加文档内容
                document.Add(new Paragraph("PDF, PDF, PDF, PDF, PDF"));
                document.Add(new Paragraph("PDF, PDF, PDF, PDF, PDF"));
                document.Add(new Paragraph("PDF, PDF, PDF, PDF, PDF"));
                document.Add(new Paragraph("PDF, PDF, PDF, PDF, PDF"));
                document.Add(new Paragraph("PDF, PDF, PDF, PDF, PDF"));
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.50所示。
 
图8.50  运行结果
查看创建的PDF文档,如图8.51所示。单击“文件”|“属性”命令,可以查看文档的信息,如图8.52所示。
图8.51  运行结果
图8.52  文档信息
8.16  新建PDF文档页
与Office中的Word文档一样,一个PDF文档是由很多PDF页面构成的,可以在C#中很方便地对这些不同的页面进行控制。本节将介绍新建PDF文档页面的内容。
1.目的说明
本实例主要介绍如何新建PDF文档页。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePdfPageDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace CreatePdfPageDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("新建文档页面");
            // 声明文档变量
            Document document = new Document();
            try
            {
                // 创建PDF文档
                PdfWriter.GetInstance(document, new FileStream(@"C:/NewPage.pdf", FileMode.Create));
                // 在第一页添加页眉
                HeaderFooter header = new HeaderFooter(new Phrase("PDF11111"), false);
                document.Header = header;
                // 打开文档
                document.Open();
                // 第二页是横向的A4
                document.SetPageSize(PageSize.A4.Rotate());
                // 添加页脚
                HeaderFooter footer = new HeaderFooter(new Phrase("PDF22222 "), true);
                document.Footer = footer;
                // 第一页内容
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                // 新建一页
                document.NewPage();
                // 第二页内容
                // 添加第二页内容
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                // 从下页开始取消页眉
                document.ResetHeader();
                // 新建一页
                document.NewPage();
                // 第三页内容
                // 添加第三页内容
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                // 重新开始页面计数
                document.ResetPageCount();
                // 新建一页
                document.NewPage();
                // 第四页
                // 添加第四页内容
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.53所示。
    
图8.53  运行结果
打开创建的PDF文档,第一页如图8.54所示。
图8.54  第一页
第二页如图8.55所示。第三页如图8.56所示。
 
图8.55  第二页                                 图8.56  第三页
第四页如图8.57所示。
图8.57  第四页
8.17  设置PDF文档的默认格式
PDF文档除了能够以默认的格式进行显示以外,还有多种其他的显示格式,这些显示格式可以在创建PDF文档时进行设置。本节介绍这方面的内容。
1.目的说明
本实例主要介绍如何设置PDF文档的默认格式。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePdfOtherDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace CreatePdfOtherDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("添加其他内容");
            // 声明文档变量
            Document document = new Document();
            try
            {
                // 创建几个PDF文档
                PdfWriter writerA = PdfWriter.GetInstance(document, new FileStream (@"C:/Other1.pdf", FileMode.Create));
                writerA.ViewerPreferences = PdfWriter.PageLayoutTwoColumnLeft;
                PdfWriter writerB = PdfWriter.GetInstance(document, new FileStream (@"C:/Other2.pdf", FileMode.Create));
                writerB.ViewerPreferences = PdfWriter.HideMenubar | PdfWriter. HideToolbar;
                PdfWriter writerC = PdfWriter.GetInstance(document, new FileStream (@"C:/Other3.pdf", FileMode.Create));
                writerC.ViewerPreferences = PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseThumbs;
                // 添加页眉
                HeaderFooter header = new HeaderFooter(new Phrase("This is a header"), false);
                document.Header = header;
                // 打开文档
                document.Open();
                // 转换为横向A4幅面
                document.SetPageSize(PageSize.A4.Rotate());
                // 添加页脚
                HeaderFooter footer = new HeaderFooter(new Phrase("This is page: "), true);
                document.Footer = footer;
                // 向页面上添加内容
                // 第一页
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                document.Add(new Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
                // 添加新页面
                document.NewPage();
                // 第二页
                // 添加第二页内容
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                document.Add(new Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
                // 取消页眉
                document.ResetHeader();
                // 添加新页面
                document.NewPage();
                // 第三页
                // 添加新内容
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                document.Add(new Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
                // 重新开始页面计数
                document.ResetPageCount();
                // 新建一页
                document.NewPage();
                // 第四页
                // 添加第四页内容
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
                document.Add(new Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
            }
            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            // 关闭文档
            document.Close();
        }
    }
}
3.运行结果
运行程序,结果如图8.58所示。
图8.58  运行结果
程序中一次创建了三个PDF文档,其中Other1.pdf如图8.59所示,即一次显示多个文档。
 
图8.59  Other1文档的显示形式 
Other2.pdf如图8.60所示,隐藏了菜单栏和工具栏,分页显示。
图8.60  Other2文档的显示形式
Other3.pdf如图8.61所示,Adobe Reader会提示是否进入全屏显示。单击“是”按钮,如图8.62所示。
 
图8.61  Other3文档的显示形式                    图8.62  Other3文档的显示形式
8.18  读取PDF文档
之前在各个实例中介绍了如何创建各种类型的PDF文档,并进行了不同的设置。本节将主要介绍如何从已有的PDF文档中读取现有的内容。
1.目的说明
本实例主要介绍如何读取PDF文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为ReadPdfDemo。
(2)添加对iTextSharp的引用。
(3)在“Program.cs”文件中添加如下引用。
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
(4)直接修改“Program.cs”文件的代码如下。
namespace ReadPdfDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("读取PDF文档");
            try
            {
                // 创建一个PdfReader对象
                PdfReader reader = new PdfReader(@"C:/origin.pdf");
                // 获得文档页数
                int n = reader.NumberOfPages;
                // 获得第一页的大小
                Rectangle psize = reader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                // 创建一个文档变量
                Document document = new Document(psize, 50, 50, 50, 50);
                // 创建该文档
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:/Read.pdf", FileMode.Create));
                // 打开文档
                document.Open();
                // 添加内容
                PdfContentByte cb = writer.DirectContent;
                int i = 0;
                int p = 0;
                Console.WriteLine("一共有 " + n + " 页.");
                while (i < n)
                {
                    document.NewPage();
                    p++;
                    i++;
                    PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                    cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);
                    Console.WriteLine("处理第 " + i + " 页");
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page2 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);
                        Console.WriteLine("处理第 " + i + " 页");
                    }
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page3 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);
                        Console.WriteLine("处理第 " + i + " 页");
                    }
                    if (i < n)
                    {
                        i++;
                        PdfImportedPage page4 = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);
                        Console.WriteLine("处理第 " + i + " 页");
                    }
                    cb.SetRGBColorStroke(255, 0, 0);
                    cb.MoveTo(0, height / 2);
                    cb.LineTo(width, height / 2);
                    cb.Stroke();
                    cb.MoveTo(width / 2, height);
                    cb.LineTo(width / 2, 0);
                    cb.Stroke();
                    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb.BeginText();
                    cb.SetFontAndSize(bf, 14);
                    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);
                    cb.EndText();
                }
                // 关闭文档
                document.Close();
            }
            catch (Exception de)
            {
                Console.Error.WriteLine(de.Message);
                Console.Error.WriteLine(de.StackTrace);
            }
        }
    }
}
3.运行结果
运行程序,结果如图8.63所示。
查看创建的PDF文档,如图8.64所示。
   
图8.63  运行结果                             图8.64  运行结果


原创粉丝点击