C#程序通过模板自动创建Word文档
添加 Microsoft.Office.Interop.Word.dll 到项目中
第一部分,代码实现
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Microsoft.Office.Interop.Word; 6 7 namespace Common.DirFile 8 { 9 public class WordDocFileHelper 10 { 11 private _Application wordApp = null; 12 private _Document wordDoc = null; 13 public _Application Application 14 { 15 get { return wordApp; } 16 set { wordApp = value; } 17 } 18 /// <summary> 19 /// 文档对象 20 /// </summary> 21 public _Document Document 22 { 23 get { return wordDoc; } 24 set { wordDoc = value; } 25 } 26 27 /// <summary> 28 /// 通过模板创建新文档 29 /// </summary> 30 /// <param name="filePath">模板文件路径</param> 31 public void CreateNewDocument(string filePath) 32 { 33 killWinWordProcess(); 34 wordApp = new ApplicationClass(); 35 wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; 36 wordApp.Visible = false; 37 object missing = System.Reflection.Missing.Value; 38 object templateName = filePath; 39 wordDoc = wordApp.Documents.Open(ref templateName, ref missing, 40 ref missing, ref missing, ref missing, ref missing, ref missing, 41 ref missing, ref missing, ref missing, ref missing, ref missing, 42 ref missing, ref missing, ref missing, ref missing); 43 } 44 45 /// <summary> 46 /// 保存新文件 47 /// </summary> 48 /// <param name="filePath">保存文件的路径</param> 49 public void SaveDocument(string filePath) 50 { 51 object fileName = filePath; 52 object format = WdSaveFormat.wdFormatDocument;//保存格式 53 object miss = System.Reflection.Missing.Value; 54 wordDoc.SaveAs(ref fileName, ref format, ref miss, 55 ref miss, ref miss, ref miss, ref miss, 56 ref miss, ref miss, ref miss, ref miss, 57 ref miss, ref miss, ref miss, ref miss, 58 ref miss); 59 //关闭wordDoc,wordApp对象 60 object SaveChanges = WdSaveOptions.wdSaveChanges; 61 object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; 62 object RouteDocument = false; 63 wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); 64 wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); 65 } 66 67 /// <summary> 68 /// 在书签处插入值 69 /// </summary> 70 /// <param name="bookmark">模板中定义的书签名</param> 71 /// <param name="value">书签处插入的内容</param> 72 /// <returns></returns> 73 public bool InsertValue(string bookmark, string value) 74 { 75 object bkObj = bookmark; 76 if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark)) 77 { 78 wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select(); 79 wordApp.Selection.TypeText(value); 80 return true; 81 } 82 return false; 83 } 84 85 /// <summary> 86 /// 插入表格,bookmark书签 87 /// </summary> 88 /// <param name="bookmark">模板中定义的书签名</param> 89 /// <param name="rows">插入表格的行数</param> 90 /// <param name="columns">插入表格的列数</param> 91 /// <param name="width"></param> 92 /// <returns></returns> 93 public Table InsertTable(string bookmark, int rows, int columns, float width) 94 { 95 object miss = System.Reflection.Missing.Value; 96 object oStart = bookmark; 97 Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 98 Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss); 99 //设置表的格式 100 newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过) 101 newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度 102 if (width != 0) 103 { 104 newTable.PreferredWidth = width;//表格宽度 105 } 106 newTable.AllowPageBreaks = false; 107 return newTable; 108 } 109 110 /// <summary> 111 /// 合并单元格 表id,开始行号,开始列号,结束行号,结束列号 112 /// </summary> 113 /// <param name="n">Table表格 索引从1开始</param> 114 /// <param name="row1">开始行号</param> 115 /// <param name="column1">开始列号</param> 116 /// <param name="row2">结束行号</param> 117 /// <param name="column2">结束列号</param> 118 public void MergeCell(int n, int row1, int column1, int row2, int column2) 119 { 120 wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2)); 121 } 122 123 /// <summary> 124 /// 合并单元格 表名,开始行号,开始列号,结束行号,结束列号 125 /// </summary> 126 /// <param name="table">Microsoft.Office.Interop.Word.Table 对象</param> 127 /// <param name="row1">开始行号</param> 128 /// <param name="column1">开始列号</param> 129 /// <param name="row2">结束行号</param> 130 /// <param name="column2">结束列号</param> 131 public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2) 132 { 133 table.Cell(row1, column1).Merge(table.Cell(row2, column2)); 134 } 135 136 /// <summary> 137 /// 设置表格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1) 138 /// Microsoft.Office.Interop.Word.Table table 139 /// </summary> 140 /// <param name="n">Table表格 索引从1开始</param> 141 /// <param name="Align">平方向:左对齐(-1),居中对齐(0),右对齐(1)</param> 142 /// <param name="Vertical">垂直方向:左对齐(-1),居中对齐(0),右对齐(1)</param> 143 public void SetParagraph_Table(int n, int Align, int Vertical) 144 { 145 switch (Align) 146 { 147 case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐 148 case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 149 case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐 150 } 151 switch (Vertical) 152 { 153 case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐 154 case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 155 case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐 156 } 157 } 158 159 /// <summary> 160 /// 设置单元格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1) 161 /// Microsoft.Office.Interop.Word.Table table 162 /// </summary> 163 /// <param name="n">Table表格 索引从1开始</param> 164 /// <param name="row">行号 索引从1开始</param> 165 /// <param name="column">列号 索引从1开始</param> 166 /// <param name="Align">平方向:左对齐(-1),居中对齐(0),右对齐(1)</param> 167 /// <param name="Vertical">垂直方向:左对齐(-1),居中对齐(0),右对齐(1)</param> 168 public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical) 169 { 170 switch (Align) 171 { 172 case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐 173 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 174 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐 175 } 176 switch (Vertical) 177 { 178 case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐 179 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 180 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐 181 } 182 183 } 184 185 /// <summary> 186 /// 设置表格字体 187 /// </summary> 188 /// <param name="table">Microsoft.Office.Interop.Word.Table 对象</param> 189 /// <param name="fontName">字体 如:宋体</param> 190 /// <param name="size">字体大小 如:9 (磅)</param> 191 public void SetFont_Table(Table table, string fontName, double size) 192 { 193 if (size != 0) 194 { 195 table.Range.Font.Size = Convert.ToSingle(size); 196 } 197 if (fontName != "") 198 { 199 table.Range.Font.Name = fontName; 200 } 201 } 202 203 /// <summary> 204 /// 设置单元格字体 Microsoft.Office.Interop.Word.Table table 205 /// </summary> 206 /// <param name="n">Table表格 索引从1开始</param> 207 /// <param name="row">行号 索引从1开始</param> 208 /// <param name="column">列号 索引从1开始</param> 209 /// <param name="fontName">字体 如:宋体</param> 210 /// <param name="size">字体大小 如:9 (磅)</param> 211 /// <param name="bold">字体加粗 </param> 212 public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold) 213 { 214 if (size != 0) 215 { 216 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size); 217 } 218 if (fontName != "") 219 { 220 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName; 221 } 222 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗体,其他值都是 223 } 224 225 /// <summary> 226 /// 是否使用边框,n表格的序号,use是或否 227 /// 该处边框参数可以用int代替bool可以让方法更全面 228 /// 具体值方法中介绍 229 /// </summary> 230 /// <param name="n">Table表格 索引从1开始</param> 231 /// <param name="use">0:无边框;1:实线边框;2、3为虚线边框;以后的数字没试过</param> 232 public void UseBorder(int n, int use) 233 { 234 wordDoc.Content.Tables[n].Borders.Enable = use; 235 } 236 237 /// <summary> 238 /// 给表格插入一行,n表格的序号从1开始记 239 /// </summary> 240 /// <param name="n">Table表格 索引从1开始</param> 241 public void AddRow(int n) 242 { 243 object miss = System.Reflection.Missing.Value; 244 wordDoc.Content.Tables[n].Rows.Add(ref miss); 245 } 246 247 /// <summary> 248 /// 给表格添加一行 249 /// </summary> 250 /// <param name="table">Microsoft.Office.Interop.Word.Table 对象</param> 251 public void AddRow(Microsoft.Office.Interop.Word.Table table) 252 { 253 object miss = System.Reflection.Missing.Value; 254 table.Rows.Add(ref miss); 255 } 256 257 /// <summary> 258 /// 给表格插入rows行,n为表格的序号 259 /// </summary> 260 /// <param name="n">Table表格 索引从1开始</param> 261 /// <param name="rows">添加位置的行号 行号索引从1开始</param> 262 public void AddRow(int n, int rows) 263 { 264 object miss = System.Reflection.Missing.Value; 265 Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; 266 for (int i = 0; i < rows; i++) 267 { 268 table.Rows.Add(ref miss); 269 } 270 } 271 272 /// <summary> 273 /// 删除表格第rows行,n为表格的序号 274 /// </summary> 275 /// <param name="n">Table表格 索引从1开始</param> 276 /// <param name="rows">删除位置的行号 行号索引从1开始</param> 277 public void DeleteRow(int n, int row) 278 { 279 Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; 280 table.Rows[row].Delete(); 281 } 282 283 /// <summary> 284 /// 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素 285 /// </summary> 286 /// <param name="table">Microsoft.Office.Interop.Word.Table 对象</param> 287 /// <param name="row">行号 索引从1开始</param> 288 /// <param name="column">列号 索引从1开始</param> 289 /// <param name="value">给单元格中添加的值</param> 290 public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value) 291 { 292 table.Cell(row, column).Range.Text = value; 293 } 294 295 /// <summary> 296 /// 给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素 297 /// </summary> 298 /// <param name="n">Table表格 索引从1开始</param> 299 /// <param name="row">行号 索引从1开始</param> 300 /// <param name="column">列号 索引从1开始</param> 301 /// <param name="value">给单元格中添加的值</param> 302 public void InsertCell(int n, int row, int column, string value) 303 { 304 wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value; 305 } 306 307 /// <summary> 308 /// 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值 309 /// </summary> 310 /// <param name="n">Table表格 索引从1开始</param> 311 /// <param name="row">行号 索引从1开始</param> 312 /// <param name="column">列号 索引从1开始</param> 313 /// <param name="values">行单元格中每一列数据合集</param> 314 public void InsertCell(int n, int row, int columns, string[] values) 315 { 316 Table table = wordDoc.Content.Tables[n]; 317 for (int i = 0; i < columns; i++) 318 { 319 table.Cell(row, i + 1).Range.Text = values[i]; 320 } 321 } 322 323 /// <summary> 324 /// 插入图片 325 /// </summary> 326 /// <param name="bookmark">模板中定义的书签名</param> 327 /// <param name="picturePath">图片的露肩</param> 328 /// <param name="width">图片宽</param> 329 /// <param name="hight">图片高</param> 330 public void InsertPicture(string bookmark, string picturePath, float width, float hight) 331 { 332 object miss = System.Reflection.Missing.Value; 333 object oStart = bookmark; 334 Object linkToFile = false; //图片是否为外部链接 335 Object saveWithDocument = true; //图片是否随文档一起保存 336 object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置 337 wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); 338 wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //设置图片宽度 339 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //设置图片高度 340 } 341 342 /// <summary> 343 /// 插入一段文字,text为文字内容 344 /// </summary> 345 /// <param name="bookmark">模板中定义的书签名</param> 346 /// <param name="text">插入的文本对象</param> 347 public void InsertText(string bookmark, string text) 348 { 349 object oStart = bookmark; 350 object range = wordDoc.Bookmarks.get_Item(ref oStart).Range; 351 Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range); 352 wp.Format.SpaceBefore = 6; 353 wp.Range.Text = text; 354 wp.Format.SpaceAfter = 24; 355 wp.Range.InsertParagraphAfter(); 356 wordDoc.Paragraphs.Last.Range.Text = "\n"; 357 } 358 359 /// <summary> 360 /// 杀掉winword.exe进程 361 /// </summary> 362 public void killWinWordProcess() 363 { 364 System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD"); 365 foreach (System.Diagnostics.Process process in processes) 366 { 367 bool b = process.MainWindowTitle == ""; 368 if (process.MainWindowTitle == "") 369 { 370 process.Kill(); 371 } 372 } 373 } 374 375 } 376 }
第二部分,具体生成文档的编码
代码见下文:
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); //文档路径
第四步,运行程序生成文档,并查看生成的文档