C#完成經由過程模板主動創立Word文檔的辦法。本站提示廣大學習愛好者:(C#完成經由過程模板主動創立Word文檔的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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#法式設計有所贊助。