C#實現通過模板自動創建Word文檔的方法
本文實例講述了C#實現通過模板自動創建Word文檔的方法,是非常實用的技巧。分享給大家供大家參考。具體實現方法如下:
引言:前段時間有項目要用c#生成Word格式的計算報告,通過網絡查找到很多內容,但是都很淩亂,於是自己決定將具體的步驟總結整理出來,以便於更好的交流和以後相似問題可以迅速的解決!
現通過具體的示例演示具體的步驟:
第一步,制作模板
1.新建一個文檔,設置文檔內容。
2.在相應位置插入書簽;將鼠標定位到要插入書簽的位置,點擊“插入”>“書簽”,彈出對話框,輸入書簽名,點擊“添加”按鈕。
3.保存模板,命名為“模板1.dot”或者“模板1.doc”
第二步,設置項目中的引用
1.右擊“解決方案資源管理器”中的項目目錄下的“引用”,選擇“添加引用”,打開“添加引用”對話框
2.在“添加引用”對話框中,選擇“COM”>“Microsoft Word 11.0 Object Library”,點擊“確定”按鈕
3.相同操作打開“添加引用”對話框中,選擇“瀏覽”項,查找到”Microsoft.Office.Interop.Word.dll”文件,選中它,點擊“確定”按鈕
註意:
此處要查找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數字
第三步,編碼
這一步分成兩個部分
第一部分,Report類的編碼
這部分我已經封裝好,為文件“Report.cs”,可以直接使用
具體實現代碼如下:(代碼中有比較詳細的註釋)
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; } } //通過模板創建新文檔 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); //關閉wordDoc,wordApp對象 objectSaveChanges =WdSaveOptions.wdSaveChanges; objectOriginalFormat =WdOriginalFormat.wdOriginalDocumentFormat; objectRouteDocument =false; wordDoc.Close(refSaveChanges, refOriginalFormat, refRouteDocument); wordApp.Quit(refSaveChanges, refOriginalFormat, refRouteDocument); } //在書簽處插入值 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書簽 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); //設置表的格式 newTable.Borders.Enable =1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過) newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//邊框寬度 if(width != 0) { newTable.PreferredWidth=width;//表格寬度 } newTable.AllowPageBreaks =false; returnnewTable; } //合並單元格 表名,開始行號,開始列號,結束行號,結束列號 publicvoidMergeCell(Microsoft.Office.Interop.Word.Tabletable, int row1, int column1,int row2, int column2) { table.Cell(row1,column1).Merge(table.Cell(row2,column2)); } //設置表格內容對齊方式Align水平方向,Vertical垂直方向(左對齊,居中對齊,右對齊分別對應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;//左對齊 case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;//水平居中 case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;//右對齊 } switch(Vertical) { case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;//頂端對齊 case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;//垂直居中 case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;//底端對齊 } } //設置表格字體 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表格的序號,use是或否 publicvoidUseBorder(int n,bool use) { if(use) { wordDoc.Content.Tables[n].Borders.Enable =1; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過) } else { wordDoc.Content.Tables[n].Borders.Enable =2; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過) } } //給表格插入一行,n表格的序號從1開始記 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為表格的序號 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行號,column列號,value插入的元素 publicvoidInsertCell(Microsoft.Office.Interop.Word.Tabletable, int row, int column,string value) { table.Cell(row,column).Range.Text =value; } //給表格中單元格插入元素,n表格的序號從1開始記,row行號,column列號,value插入的元素 publicvoidInsertCell(int n, int row,int column, string value) { wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value; } //給表格插入一行數據,n為表格的序號,row行號,columns列數,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; //設置圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; //設置圖片高度 } //插入一段文字,text為文字內容 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進程 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(); } } } } }
第二部分,具體生成文檔的編碼
代碼見下文:
1.首先需要載入模板
Report report =new Report();
report.CreateNewDocument(TemPath); //模板路徑
2.插入一個值
report.InsertValue(“Bookmark_value”,”世界杯”);//在書簽“Bookmark_value”處插入值
3.創建一個表格
Table table =report.InsertTable(“Bookmark_table”, 2, 3, 0); //在書簽“Bookmark_table”處插入2行3列行寬最大的表
4.合並單元格
report.MergeCell(table, 1, 1, 1, 3); //表名,開始行號,開始列號,結束行號,結束列號
5.表格添加一行
report.AddRow(table); //表名
6.在單元格中插入值
report.InsertCell(table, 2, 1,”R2C1″);//表名,行號,列號,值
7.設置表格中文字的對齊方式
report.SetParagraph_Table(table, -1, 0);//水平方向左對齊,垂直方向居中對齊
8.設置表格字體
report.SetFont_Table(table,”宋體”, 9);//宋體9磅
9.給現有的表格添加一行
report.AddRow(1);//給模板中第一個表格添加一行
10.確定現有的表格是否使用邊框
report.UseBorder(1,true); //模板中第一個表格使用實線邊框
11.給現有的表格添加多行
report.AddRow(1, 2);//給模板中第一個表格插入2行
12.給現有的表格插入一行數據
string[] values={“英超”, “意甲”, “德甲”,”西甲”, “法甲” };
report.InsertCell(1, 2, 5,values); //給模板中第一個表格的第二行的5列分別插入數據
13.插入圖片
string picturePath = @”C:\Documents and Settings\Administrator\桌面\1.jpg”;
report.InsertPicture(“Bookmark_picture”,picturePath, 150, 150); //書簽位置,圖片路徑,圖片寬度,圖片高度
14.插入一段文字
string text = “長期從事電腦操作者,應多吃一些新鮮的蔬菜和水果,同時增加維生素A、B1、C、E的攝入。為預防角膜幹燥、眼幹澀、視力下降、甚至出現夜盲等,電 腦操作者應多吃富含維生素A的食物,如豆制品、魚、牛奶、核桃、青菜、大白菜、空心菜、西紅柿及新鮮水果等。”;
report.InsertText(“Bookmark_text”,text);
15.最後保存文檔
report.SaveDocument(RepPath); //文檔路徑
第四步,運行程序生成文檔,並查看生成的文檔
希望本文所述對大家的C#程序設計有所幫助。
除聲明外,跑步客文章均為原創,轉載請以鏈接形式標明本文地址C#實現通過模板自動創建Word文檔的方法
本文地址: http://www.paobuke.com/develop/c-develop/pbk23495.html
相關內容
C# FileStream???t?áD′?ê?aC#簡單實現防止多個程序運行的方法C#訪問SQL Server數據庫的實現方法C#實現利用Windows API讀寫INI文件的方法C#生成Word文檔代碼示例C#中的文件路徑獲取函數和文件名字獲取函數小結C#實現終止正在執行的線程C#使用ping命令的兩個例子
C#實現通過模板自動創建Word文檔的方法