C#實(shí)現(xiàn)通過(guò)模板自動(dòng)創(chuàng)建Word文檔的方法
本文實(shí)例講述了C#實(shí)現(xiàn)通過(guò)模板自動(dòng)創(chuàng)建Word文檔的方法,是非常實(shí)用的技巧。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
引言:前段時(shí)間有項(xiàng)目要用c#生成Word格式的計(jì)算報(bào)告,通過(guò)網(wǎng)絡(luò)查找到很多內(nèi)容,但是都很凌亂,于是自己決定將具體的步驟總結(jié)整理出來(lái),以便于更好的交流和以后相似問(wèn)題可以迅速的解決!
現(xiàn)通過(guò)具體的示例演示具體的步驟:
第一步,制作模板
1.新建一個(gè)文檔,設(shè)置文檔內(nèi)容。
2.在相應(yīng)位置插入書(shū)簽;將鼠標(biāo)定位到要插入書(shū)簽的位置,點(diǎn)擊“插入”>“書(shū)簽”,彈出對(duì)話框,輸入書(shū)簽名,點(diǎn)擊“添加”按鈕。
3.保存模板,命名為“模板1.dot”或者“模板1.doc”
第二步,設(shè)置項(xiàng)目中的引用
1.右擊“解決方案資源管理器”中的項(xiàng)目目錄下的“引用”,選擇“添加引用”,打開(kāi)“添加引用”對(duì)話框
2.在“添加引用”對(duì)話框中,選擇“COM”>“Microsoft Word 11.0 Object Library”,點(diǎn)擊“確定”按鈕
3.相同操作打開(kāi)“添加引用”對(duì)話框中,選擇“瀏覽”項(xiàng),查找到”Microsoft.Office.Interop.Word.dll”文件,選中它,點(diǎn)擊“確定”按鈕
注意:此處要查找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數(shù)字
第三步,編碼
這一步分成兩個(gè)部分
第一部分,Report類的編碼
這部分我已經(jīng)封裝好,為文件“Report.cs”,可以直接使用
具體實(shí)現(xiàn)代碼如下:(代碼中有比較詳細(xì)的注釋)
using System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.Word; namespace MYNAMESPACE //這邊需要換成自己的命名空間名 { classReport { private_ApplicationwordApp= null; private_DocumentwordDoc= null; public_ApplicationApplication { get { return wordApp; } set { wordApp = value; } } public_DocumentDocument { get { return wordDoc; } set { wordDoc = value; } } //通過(guò)模板創(chuàng)建新文檔 publicvoidCreateNewDocument(stringfilePath) { killWinWordProcess(); wordApp= new ApplicationClass(); wordApp.DisplayAlerts =WdAlertLevel.wdAlertsNone; wordApp.Visible =false; objectmissing =System.Reflection.Missing.Value; objecttemplateName =filePath; wordDoc= wordApp.Documents.Open(reftemplateName, refmissing, ref missing, ref missing,ref missing, ref missing, refmissing, ref missing, ref missing,ref missing, ref missing, refmissing, ref missing, ref missing,ref missing, ref missing); } //保存新文件 publicvoidSaveDocument(stringfilePath) { objectfileName =filePath; objectformat =WdSaveFormat.wdFormatDocument;//保存格式 objectmiss =System.Reflection.Missing.Value; wordDoc.SaveAs(reffileName, ref format, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss); //關(guān)閉wordDoc,wordApp對(duì)象 objectSaveChanges =WdSaveOptions.wdSaveChanges; objectOriginalFormat =WdOriginalFormat.wdOriginalDocumentFormat; objectRouteDocument =false; wordDoc.Close(refSaveChanges, refOriginalFormat, refRouteDocument); wordApp.Quit(refSaveChanges, refOriginalFormat, refRouteDocument); } //在書(shū)簽處插入值 publicboolInsertValue(stringbookmark, stringvalue) { objectbkObj =bookmark; if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark)) { wordApp.ActiveDocument.Bookmarks.get_Item(refbkObj).Select(); wordApp.Selection.TypeText(value); return true; } returnfalse; } //插入表格,bookmark書(shū)簽 publicTableInsertTable(stringbookmark, int rows, int columns,float width) { objectmiss =System.Reflection.Missing.Value; objectoStart =bookmark; Rangerange =wordDoc.Bookmarks.get_Item(refoStart).Range;//表格插入位置 TablenewTable =wordDoc.Tables.Add(range,rows, columns, ref miss, refmiss); //設(shè)置表的格式 newTable.Borders.Enable =1; //允許有邊框,默認(rèn)沒(méi)有邊框(為0時(shí)報(bào)錯(cuò),1為實(shí)線邊框,2、3為虛線邊框,以后的數(shù)字沒(méi)試過(guò)) newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//邊框?qū)挾? if(width != 0) { newTable.PreferredWidth=width;//表格寬度 } newTable.AllowPageBreaks =false; returnnewTable; } //合并單元格 表名,開(kāi)始行號(hào),開(kāi)始列號(hào),結(jié)束行號(hào),結(jié)束列號(hào) publicvoidMergeCell(Microsoft.Office.Interop.Word.Tabletable, int row1, int column1,int row2, int column2) { table.Cell(row1,column1).Merge(table.Cell(row2,column2)); } //設(shè)置表格內(nèi)容對(duì)齊方式Align水平方向,Vertical垂直方向(左對(duì)齊,居中對(duì)齊,右對(duì)齊分別對(duì)應(yīng)Align和Vertical的值為-1,0,1) publicvoidSetParagraph_Table(Microsoft.Office.Interop.Word.Tabletable, int Align, int Vertical) { switch(Align) { case -1:table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;break;//左對(duì)齊 case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;//水平居中 case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;//右對(duì)齊 } switch(Vertical) { case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;//頂端對(duì)齊 case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;//垂直居中 case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;//底端對(duì)齊 } } //設(shè)置表格字體 publicvoidSetFont_Table(Microsoft.Office.Interop.Word.Tabletable, string fontName, double size) { if(size != 0) { table.Range.Font.Size =Convert.ToSingle(size); } if(fontName !="") { table.Range.Font.Name =fontName; } } //是否使用邊框,n表格的序號(hào),use是或否 publicvoidUseBorder(int n,bool use) { if(use) { wordDoc.Content.Tables[n].Borders.Enable =1; //允許有邊框,默認(rèn)沒(méi)有邊框(為0時(shí)無(wú)邊框,1為實(shí)線邊框,2、3為虛線邊框,以后的數(shù)字沒(méi)試過(guò)) } else { wordDoc.Content.Tables[n].Borders.Enable =2; //允許有邊框,默認(rèn)沒(méi)有邊框(為0時(shí)無(wú)邊框,1為實(shí)線邊框,2、3為虛線邊框,以后的數(shù)字沒(méi)試過(guò)) } } //給表格插入一行,n表格的序號(hào)從1開(kāi)始記 publicvoidAddRow(int n) { objectmiss =System.Reflection.Missing.Value; wordDoc.Content.Tables[n].Rows.Add(refmiss); } //給表格添加一行 publicvoidAddRow(Microsoft.Office.Interop.Word.Tabletable) { objectmiss =System.Reflection.Missing.Value; table.Rows.Add(refmiss); } //給表格插入rows行,n為表格的序號(hào) publicvoidAddRow(int n, int rows) { objectmiss =System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n]; for(inti = 0; i < rows; i++) { table.Rows.Add(refmiss); } } //給表格中單元格插入元素,table所在表格,row行號(hào),column列號(hào),value插入的元素 publicvoidInsertCell(Microsoft.Office.Interop.Word.Tabletable, int row, int column,string value) { table.Cell(row,column).Range.Text =value; } //給表格中單元格插入元素,n表格的序號(hào)從1開(kāi)始記,row行號(hào),column列號(hào),value插入的元素 publicvoidInsertCell(int n, int row,int column, string value) { wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value; } //給表格插入一行數(shù)據(jù),n為表格的序號(hào),row行號(hào),columns列數(shù),values插入的值 publicvoidInsertCell(int n, int row,int columns, string[] values) { Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n]; for(inti = 0; i < columns; i++) { table.Cell(row,i + 1).Range.Text =values[i]; } } //插入圖片 publicvoidInsertPicture(stringbookmark, stringpicturePath, floatwidth, float hight) { object miss = System.Reflection.Missing.Value; objectoStart =bookmark; ObjectlinkToFile =false; //圖片是否為外部鏈接 ObjectsaveWithDocument =true; //圖片是否隨文檔一起保存 objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;//圖片插入位置 wordDoc.InlineShapes.AddPicture(picturePath,ref linkToFile, ref saveWithDocument, refrange); wordDoc.Application.ActiveDocument.InlineShapes[1].Width=width; //設(shè)置圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; //設(shè)置圖片高度 } //插入一段文字,text為文字內(nèi)容 publicvoidInsertText(stringbookmark, stringtext) { objectoStart =bookmark; objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range; Paragraphwp =wordDoc.Content.Paragraphs.Add(refrange); wp.Format.SpaceBefore= 6; wp.Range.Text =text; wp.Format.SpaceAfter =24; wp.Range.InsertParagraphAfter(); wordDoc.Paragraphs.Last.Range.Text ="\n"; } //殺掉winword.exe進(jìn)程 publicvoidkillWinWordProcess() { System.Diagnostics.Process[]processes=System.Diagnostics.Process.GetProcessesByName("WINWORD"); foreach (System.Diagnostics.Processprocess in processes) { bool b = process.MainWindowTitle==""; if (process.MainWindowTitle =="") { process.Kill(); } } } } }
第二部分,具體生成文檔的編碼
代碼見(jiàn)下文:
1.首先需要載入模板
Report report =new Report();
report.CreateNewDocument(TemPath); //模板路徑
2.插入一個(gè)值
report.InsertValue("Bookmark_value","世界杯");//在書(shū)簽“Bookmark_value”處插入值
3.創(chuàng)建一個(gè)表格
Table table =report.InsertTable("Bookmark_table", 2, 3, 0); //在書(shū)簽“Bookmark_table”處插入2行3列行寬最大的表
4.合并單元格
report.MergeCell(table, 1, 1, 1, 3); //表名,開(kāi)始行號(hào),開(kāi)始列號(hào),結(jié)束行號(hào),結(jié)束列號(hào)
5.表格添加一行
report.AddRow(table); //表名
6.在單元格中插入值
report.InsertCell(table, 2, 1,"R2C1");//表名,行號(hào),列號(hào),值
7.設(shè)置表格中文字的對(duì)齊方式
report.SetParagraph_Table(table, -1, 0);//水平方向左對(duì)齊,垂直方向居中對(duì)齊
8.設(shè)置表格字體
report.SetFont_Table(table,"宋體", 9);//宋體9磅
9.給現(xiàn)有的表格添加一行
report.AddRow(1);//給模板中第一個(gè)表格添加一行
10.確定現(xiàn)有的表格是否使用邊框
report.UseBorder(1,true); //模板中第一個(gè)表格使用實(shí)線邊框
11.給現(xiàn)有的表格添加多行
report.AddRow(1, 2);//給模板中第一個(gè)表格插入2行
12.給現(xiàn)有的表格插入一行數(shù)據(jù)
string[] values={"英超", "意甲", "德甲","西甲", "法甲" };
report.InsertCell(1, 2, 5,values); //給模板中第一個(gè)表格的第二行的5列分別插入數(shù)據(jù)
13.插入圖片
string picturePath = @"C:\Documents and Settings\Administrator\桌面\1.jpg";
report.InsertPicture("Bookmark_picture",picturePath, 150, 150); //書(shū)簽位置,圖片路徑,圖片寬度,圖片高度
14.插入一段文字
string text = "長(zhǎng)期從事電腦操作者,應(yīng)多吃一些新鮮的蔬菜和水果,同時(shí)增加維生素A、B1、C、E的攝入。為預(yù)防角膜干燥、眼干澀、視力下降、甚至出現(xiàn)夜盲等,電 腦操作者應(yīng)多吃富含維生素A的食物,如豆制品、魚(yú)、牛奶、核桃、青菜、大白菜、空心菜、西紅柿及新鮮水果等。";
report.InsertText("Bookmark_text",text);
15.最后保存文檔
report.SaveDocument(RepPath); //文檔路徑
第四步,運(yùn)行程序生成文檔,并查看生成的文檔
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
關(guān)于C# TabPage如何隱藏的問(wèn)題
TabPage沒(méi)有Visible屬性,所以只能通過(guò)設(shè)置將其與父控件(tabcontrol)的關(guān)聯(lián)性去除就好了,如下面代碼:2013-04-04C#微信公眾平臺(tái)開(kāi)發(fā)之高級(jí)群發(fā)接口
這篇文章主要為大家詳細(xì)介紹了C#微信公眾平臺(tái)開(kāi)發(fā)之高級(jí)群發(fā)接口的相關(guān)資料,需要的朋友可以參考下2016-03-03基于C#實(shí)現(xiàn)簡(jiǎn)單的二維碼和條形碼的生成工具
這篇文章主要為大家詳細(xì)介紹了如何基于C#實(shí)現(xiàn)簡(jiǎn)單的二維碼和條形碼工具,用于二維碼條形碼的生成與識(shí)別,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12Unity3D實(shí)現(xiàn)人物移動(dòng)示例
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)人物移動(dòng)示例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01C# ODP.NET 調(diào)用Oracle函數(shù)返回值時(shí)報(bào)錯(cuò)的一個(gè)解決方案
這篇文章主要介紹了C# ODP.NET 調(diào)用Oracle函數(shù)返回值時(shí)報(bào)錯(cuò)的一個(gè)解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12