C# 操作 word

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,Word2003對應11.0。通過在項目中添加該組件,即可使用微軟公司提供的方法創建相應版本的Word文檔。

1.目的說明

介紹創建Word文檔的基本知識,通過實例演示如何創建Word 2003版本的Word文檔和Word2007版本的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版本系列創建的文檔,本節首先使用MicrosoftWord 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.ApplicationwordApp;              //Word應用程序變量

       MSWord.DocumentwordDoc;             //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, refNothing);

       //WdSaveFormat爲Word文檔的保存格式

       object format =MSWord.WdSaveFormat.wdFormatDocument;

        //將wordDoc文檔對象的內容保存爲DOC文檔

       wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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)

    {

        objectpath;                         //文件路徑變量

        stringstrContent;                   //文本內容變量

       MSWord.ApplicationwordApp;              //Word應用程序變量

       MSWord.Document wordDoc;             //Word文檔變量

       

        path =@"C:\MyWord.docx";            //路徑

        wordApp = newMSWord.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(refpath, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing);

        //關閉wordDoc文檔對象

        wordDoc.Close(refNothing, 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;                            //文件路徑變量

        stringstrContent;                      //文本內容變量

       MSWord.Application wordApp;                  //Word應用程序變量

        MSWord.DocumentwordDoc;                 //Word文檔變量

       

        path =@"C:\MyWord.docx";                   //路徑

        wordApp = newMSWord.ApplicationClass(); //初始化

        //如果已存在,則刪除

        if(File.Exists((string)path))

        {

           File.Delete((string)path);

        }

        //由於使用的是COM庫,因此有許多變量需要用Missing.Value代替

         ObjectNothing = 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, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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 XObject 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;                            //文件路徑變量

        stringstrContent;                      //文本內容變量

       MSWord.Application wordApp;                  //Word應用程序變量

       MSWord.Document wordDoc;                 //Word文檔變量

        

        path =@"C:\MyWord.docx";                   //路徑

        wordApp = newMSWord.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, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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文檔中添加表格

除了簡單的文本信息外,MicrosoftWord也是一個處理表格的強大工具。許多數據報表也需要通過表格的形式在Word中體現。本節將介紹如何使用C#在Word中創建一個表格。

表格是由Microsoft WordX 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;                       //文件路徑變量

        stringstrContent;                  //文本內容變量

       MSWord.Application wordApp;              //Word應用程序變量

       MSWord.Document wordDoc;             //Word文檔變量

       

        path =@"C:\MyWord.docx";               //路徑

        wordApp = newMSWord.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.Tabletable = wordDoc.Tables.Add(wordApp.Selection.Range, 5, 5, ref Nothing, refNothing);

           //默認創建的表格沒有邊框,這裏修改其屬性,使得創建的表格帶有邊框

           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, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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.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;                            //文件路徑變量

        stringstrContent;                      //文本內容變量

       MSWord.Application wordApp;                  //Word應用程序變量

       MSWord.Document wordDoc;                 //Word文檔變量

        path =@"C:\MyWord.docx";                //路徑

        wordApp = newMSWord.ApplicationClass(); //初始化

        //如果已存在,則刪除

        if(File.Exists((string)path))

        {

           File.Delete((string)path);

        }

        //由於使用的是COM庫,因此有許多變量需要用Missing.Value代替

        Object Nothing= Missing.Value;

        wordDoc = wordApp.Documents.Add(refNothing, ref Nothing, ref Nothing, ref Nothing);

        //圖片文件的路徑

        stringfilename = @"C:\BackgroundImage.jpg";

        //要向Word文檔中插入圖片的位置

        Object range =wordDoc.Paragraphs.Last.Range;

        //定義該插入的圖片是否爲外部鏈接

        ObjectlinkToFile =false;               //默認

        //定義要插入的圖片是否隨Word文檔一起保存

        ObjectsaveWithDocument =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, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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 Excel X Object Library的引用,其中的X對應爲版本號。Excel 2007對應12.0。在MicrosoftExcel X 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 = newMSExcel.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, refNothing);

       //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, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, 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.7 使用C#向Excel文檔中寫入數據

Microsoft Excel的強大功能就在於其數據處理功能,用戶可以通過其方便的操作和強大的公式和圖表處理現有的數據。本節介紹如何使用C#向Excel文檔中寫入數據。

在Excel文檔中,數據是有明確的標識的,一般由其行名稱和列名稱進行標識。在C#中向Excel文檔寫入數據時,MicrosoftExcel X 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.WorkbookexcelDoc;                   //Excel文檔變量

        

        path =@"C:\MyExcel.xlsx";                  //路徑

        excelApp = newMSExcel.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.Ranger;

        //獲得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 = newMSExcel.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.Ranger;

        //獲得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文檔

MicrosoftPowerPoint是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.34PpSaveAsFileFormat枚舉                  圖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文檔。該文檔是MicrosoftPowerPoint 2003支持的文檔格式,大小約爲25KB。

8.10 使用C#向PowerPoint文檔中寫入數據

MicrosoftPowerPoint的強大就在於其演示功能,用戶可以通過其方便的操作和易用的特性形成一個漂亮的演示文檔。本節將介紹如何使用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;

usingiTextSharp.text;

usingiTextSharp.text.pdf;

(4)直接修改“Program.cs”文件的代碼如下。

namespaceSetPdfSizeDemo

{

   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;

usingSystem.Diagnostics;

usingiTextSharp.text;

usingiTextSharp.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;

usingiTextSharp.text;

usingiTextSharp.text.pdf;

(4)直接修改“Program.cs”文件的代碼如下。

namespaceSetPdfInfoDemo

{

   class Program

   {

       static void Main(string[] args)

       {

           Console.WriteLine("設置信息");

           // 聲明文檔變量

           Document document = new Document();

           try

           {

               // 創建文檔

                PdfWriter.GetInstance(document, newFileStream(@"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(newParagraph("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 運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章