C#實現(xiàn)通過模板自動創(chuàng)建Word文檔的方法
本文實例講述了C#實現(xiàn)通過模板自動創(chuàng)建Word文檔的方法,是非常實用的技巧。分享給大家供大家參考。具體實現(xiàn)方法如下:
引言:前段時間有項目要用c#生成Word格式的計算報告,通過網(wǎng)絡(luò)查找到很多內(nèi)容,但是都很凌亂,于是自己決定將具體的步驟總結(jié)整理出來,以便于更好的交流和以后相似問題可以迅速的解決!
現(xiàn)通過具體的示例演示具體的步驟:
第一步,制作模板
1.新建一個文檔,設(shè)置文檔內(nèi)容。
2.在相應位置插入書簽;將鼠標定位到要插入書簽的位置,點擊“插入”>“書簽”,彈出對話框,輸入書簽名,點擊“添加”按鈕。
3.保存模板,命名為“模板1.dot”或者“模板1.doc”
第二步,設(shè)置項目中的引用
1.右擊“解決方案資源管理器”中的項目目錄下的“引用”,選擇“添加引用”,打開“添加引用”對話框
2.在“添加引用”對話框中,選擇“COM”>“Microsoft Word 11.0 Object Library”,點擊“確定”按鈕
3.相同操作打開“添加引用”對話框中,選擇“瀏覽”項,查找到”Microsoft.Office.Interop.Word.dll”文件,選中它,點擊“確定”按鈕
注意:此處要查找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數(shù)字
第三步,編碼
這一步分成兩個部分
第一部分,Report類的編碼
這部分我已經(jīng)封裝好,為文件“Report.cs”,可以直接使用
具體實現(xiàn)代碼如下:(代碼中有比較詳細的注釋)
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;
}
}
//通過模板創(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對象
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);
//設(shè)置表的格式
newTable.Borders.Enable =1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以后的數(shù)字沒試過)
newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//邊框?qū)挾?
if(width != 0)
{
newTable.PreferredWidth=width;//表格寬度
}
newTable.AllowPageBreaks =false;
returnnewTable;
}
//合并單元格 表名,開始行號,開始列號,結(jié)束行號,結(jié)束列號
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)容對齊方式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;//底端對齊
}
}
//設(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表格的序號,use是或否
publicvoidUseBorder(int n,bool use)
{
if(use)
{
wordDoc.Content.Tables[n].Borders.Enable =1; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以后的數(shù)字沒試過)
}
else
{
wordDoc.Content.Tables[n].Borders.Enable =2; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以后的數(shù)字沒試過)
}
}
//給表格插入一行,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;
}
//給表格插入一行數(shù)據(jù),n為表格的序號,row行號,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進程
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.創(chuàng)建一個表格
Table table =report.InsertTable("Bookmark_table", 2, 3, 0); //在書簽“Bookmark_table”處插入2行3列行寬最大的表
4.合并單元格
report.MergeCell(table, 1, 1, 1, 3); //表名,開始行號,開始列號,結(jié)束行號,結(jié)束列號
5.表格添加一行
report.AddRow(table); //表名
6.在單元格中插入值
report.InsertCell(table, 2, 1,"R2C1");//表名,行號,列號,值
7.設(shè)置表格中文字的對齊方式
report.SetParagraph_Table(table, -1, 0);//水平方向左對齊,垂直方向居中對齊
8.設(shè)置表格字體
report.SetFont_Table(table,"宋體", 9);//宋體9磅
9.給現(xiàn)有的表格添加一行
report.AddRow(1);//給模板中第一個表格添加一行
10.確定現(xiàn)有的表格是否使用邊框
report.UseBorder(1,true); //模板中第一個表格使用實線邊框
11.給現(xiàn)有的表格添加多行
report.AddRow(1, 2);//給模板中第一個表格插入2行
12.給現(xiàn)有的表格插入一行數(shù)據(jù)
string[] values={"英超", "意甲", "德甲","西甲", "法甲" };
report.InsertCell(1, 2, 5,values); //給模板中第一個表格的第二行的5列分別插入數(shù)據(jù)
13.插入圖片
string picturePath = @"C:\Documents and Settings\Administrator\桌面\1.jpg";
report.InsertPicture("Bookmark_picture",picturePath, 150, 150); //書簽位置,圖片路徑,圖片寬度,圖片高度
14.插入一段文字
string text = "長期從事電腦操作者,應多吃一些新鮮的蔬菜和水果,同時增加維生素A、B1、C、E的攝入。為預防角膜干燥、眼干澀、視力下降、甚至出現(xiàn)夜盲等,電 腦操作者應多吃富含維生素A的食物,如豆制品、魚、牛奶、核桃、青菜、大白菜、空心菜、西紅柿及新鮮水果等。";
report.InsertText("Bookmark_text",text);
15.最后保存文檔
report.SaveDocument(RepPath); //文檔路徑
第四步,運行程序生成文檔,并查看生成的文檔
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C# ODP.NET 調(diào)用Oracle函數(shù)返回值時報錯的一個解決方案
這篇文章主要介紹了C# ODP.NET 調(diào)用Oracle函數(shù)返回值時報錯的一個解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12

