執行個體開發:利用 Visual C# .NET 使 Word 自動建立文檔?

來源:互聯網
上載者:User
本文中的程式碼範例將說明如何完成以下任務:

插入包含文本和格式的段落。
瀏覽和修改文檔中的不同範圍。
插入表格、設定表格格式並在表格中填充資料。
添加圖表。

要利用 Visual C# .NET 的自動化功能建立新的 Word 文檔,請執行以下步驟:

1. 啟動 Microsoft Visual Studio .NET。在檔案菜單上,單擊建立,然後單擊項目。在項目類型下,單擊 Visual C# 項目,然後單擊模板下的 Windows 應用程式。預設情況下會建立 Form1。
2. 添加對 Microsoft Word 物件程式庫的引用。為此,請按照下列步驟操作:

a. 項目菜單上,單擊添加引用
b. COM 選項卡上,找到 Microsoft Word 物件程式庫,然後單擊選擇
c. 添加引用對話方塊中單擊確定,接受您的選擇。如果系統提示您為選定的庫產生封裝,請單擊
3. 視圖菜單上,選擇工具箱以顯示工具箱,然後向 Form1 添加一個按鈕。
4. 雙擊 Button1。出現該表單的代碼視窗。
5. 在代碼視窗中,將以下代碼

private void button1_Click(object sender, System.EventArgs e)            {            }            

替換為:

private void button1_Click(object sender, System.EventArgs e)            {            object oMissing = System.Reflection.Missing.Value;            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */            //Start Word and create a new document.            Word._Application oWord;            Word._Document oDoc;            oWord = new Word.Application();            oWord.Visible = true;            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,            ref oMissing, ref oMissing);            //Insert a paragraph at the beginning of the document.            Word.Paragraph oPara1;            oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);            oPara1.Range.Text = "Heading 1";            oPara1.Range.Font.Bold = 1;            oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.            oPara1.Range.InsertParagraphAfter();            //Insert a paragraph at the end of the document.            Word.Paragraph oPara2;            object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);            oPara2.Range.Text = "Heading 2";            oPara2.Format.SpaceAfter = 6;            oPara2.Range.InsertParagraphAfter();            //Insert another paragraph.            Word.Paragraph oPara3;            oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);            oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";            oPara3.Range.Font.Bold = 0;            oPara3.Format.SpaceAfter = 24;            oPara3.Range.InsertParagraphAfter();            //Insert a 3 x 5 table, fill it with data, and make the first row            //bold and italic.            Word.Table oTable;            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);            oTable.Range.ParagraphFormat.SpaceAfter = 6;            int r, c;            string strText;            for(r = 1; r <= 3; r++)            for(c = 1; c <= 5; c++)            {            strText = "r" + r + "c" + c;            oTable.Cell(r, c).Range.Text = strText;            }            oTable.Rows[1].Range.Font.Bold = 1;            oTable.Rows[1].Range.Font.Italic = 1;            //Add some text after the table.            Word.Paragraph oPara4;            oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);            oPara4.Range.InsertParagraphBefore();            oPara4.Range.Text = "And here's another table:";            oPara4.Format.SpaceAfter = 24;            oPara4.Range.InsertParagraphAfter();            //Insert a 5 x 2 table, fill it with data, and change the column widths.            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);            oTable.Range.ParagraphFormat.SpaceAfter = 6;            for(r = 1; r <= 5; r++)            for(c = 1; c <= 2; c++)            {            strText = "r" + r + "c" + c;            oTable.Cell(r, c).Range.Text = strText;            }            oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2            oTable.Columns[2].Width = oWord.InchesToPoints(3);            //Keep inserting text. When you get to 7 inches from top of the            //document, insert a hard page break.            object oPos;            double dPos = oWord.InchesToPoints(7);            oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();            do            {            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            wrdRng.ParagraphFormat.SpaceAfter = 6;            wrdRng.InsertAfter("A line of text");            wrdRng.InsertParagraphAfter();            oPos = wrdRng.get_Information            (Word.WdInformation.wdVerticalPositionRelativeToPage);            }            while(dPos >= Convert.ToDouble(oPos));            object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;            object oPageBreak = Word.WdBreakType.wdPageBreak;            wrdRng.Collapse(ref oCollapseEnd);            wrdRng.InsertBreak(ref oPageBreak);            wrdRng.Collapse(ref oCollapseEnd);            wrdRng.InsertAfter("We're now on page 2. Here's my chart:");            wrdRng.InsertParagraphAfter();            //Insert a chart.            Word.InlineShape oShape;            object oClassType = "MSGraph.Chart.8";            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,            ref oMissing, ref oMissing, ref oMissing,            ref oMissing, ref oMissing, ref oMissing);            //Demonstrate use of late bound oChart and oChartApp objects to            //manipulate the chart object with MSGraph.            object oChart;            object oChartApp;            oChart = oShape.OLEFormat.Object;            oChartApp = oChart.GetType().InvokeMember("Application",            BindingFlags.GetProperty, null, oChart, null);            //Change the chart type to Line.            object[] Parameters = new Object[1];            Parameters[0] = 4; //xlLine = 4            oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,            null, oChart, Parameters);            //Update the chart image and quit MSGraph.            oChartApp.GetType().InvokeMember("Update",            BindingFlags.InvokeMethod, null, oChartApp, null);            oChartApp.GetType().InvokeMember("Quit",            BindingFlags.InvokeMethod, null, oChartApp, null);            //... If desired, you can proceed from here using the Microsoft Graph            //Object model on the oChart and oChartApp objects to make additional            //changes to the chart.            //Set the width of the chart.            oShape.Width = oWord.InchesToPoints(6.25f);            oShape.Height = oWord.InchesToPoints(3.57f);            //Add text after the chart.            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;            wrdRng.InsertParagraphAfter();            wrdRng.InsertAfter("THE END.");            //Close this form.            this.Close();            }            

6. 滾動到代碼視窗的頂部。將下面的程式碼添加到 using 指令列表的末尾:

using Word = Microsoft.Office.Interop.Word;            using System.Reflection;            

7. 按 F5 鍵產生並運行程式。
8. 單擊 Button1,啟動 Word 自動化功能並建立文檔。

代碼執行完成後,檢查為您建立的文檔。該文檔包含兩頁設定了格式的段落、表格和圖表。

使用模板

如果您要使用自動化功能建立的文檔都是通用格式,則利用基於預設格式的模板的新文檔來開始建立過程會更加容易。與從頭建立文檔相比,將某個模板與 Word 自動化用戶端配合使用有兩大優點:

您可以對整個文檔中的對象的格式設定和布局施加更多控制。
可以使用較少的代碼建立文檔。

通過使用模板,可以精確地調整表格、段落和其他對象在文檔中的布局,並可為這些對象添加格式設定。通過使用自動化功能,可以基於包含下面這樣的代碼的模板建立新文檔:

object oTemplate = "c:\\MyTemplate.dot";oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,ref oMissing, ref oMissing);

在模板中,可以定義書籤,這樣,自動化用戶端就可以在文檔的特定位置加入可變文本,如下所示:

object oBookMark = "MyBookmark";oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

使用模板的另一個優點在於,您可以建立和儲存希望在運行時應用的格式樣式,如下所示:

object oStyleName = "MyStyle";oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

- 或者 -

object oStyleName = "MyStyle";oWord.Selection.set_Style(ref oStyleName);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.