愤斗的程序猿丷
Keep on going never give up.

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

简单的使用例子:

1、先建好Word文档,设置好排版、插入标签

2、代码如下:

private void button1_Click(object sender, EventArgs e)
        {
            Report report = new Report();
            report.CreateNewDocument(Application.StartupPath + "\\WordDome.doc"); //模板路径
            report.InsertValue("date1", "09月04日");//在书签处插入值
            report.InsertValue("date2", "09月05日");
            report.InsertValue("date3", "09月06日");
            report.InsertValue("date4", "09月07日");
            report.InsertValue("date5", "09月08日");
            report.InsertValue("date6", "09月09日");
            report.InsertValue("date7", "09月10日");

            DataTable dtSource= GetTestDT();

            int xx = dtSource.Rows.Count;
            report.AddRow(1, xx);
            for (int i = 0; i < xx; i++)
            {
                string[] values = { dtSource.Rows[i]["DEPT_NAME"].ToString(), dtSource.Rows[i]["C1"].ToString(), dtSource.Rows[i]["C2"].ToString(), dtSource.Rows[i]["C3"].ToString(), 
                                      dtSource.Rows[i]["C4"].ToString(),dtSource.Rows[i]["C5"].ToString(), dtSource.Rows[i]["C6"].ToString(), dtSource.Rows[i]["C7"].ToString()};
                report.InsertCell(1, 3 + i, 8, values); // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
            }
       string savename = @"D:\WordDemo" + DateTime.Now.ToString("yyyyMMdd").Trim() + ".doc";//默认名称
       SaveFileDialog saveFileDialog = new SaveFileDialog();
       saveFileDialog.Filter = "doc|*.doc|所有文件|*.*";
       saveFileDialog.FilterIndex = 1;
       saveFileDialog.FileName = savename;
       saveFileDialog.RestoreDirectory = true;
       if (saveFileDialog.ShowDialog() == DialogResult.OK)
       {
         savename = saveFileDialog.FileName;//设置保存的路径及文件名
       }
       try
       {
         report.SaveDocument(savename);//保存文件
         MessageBox.Show("保存成功!", "提示");
       }
       catch(Exception ex)
       { 
         MessageBox.Show("保存失败:"+ex, "提示"); 
       }
        }

 

posted on 2018-02-09 09:04  愤斗的程序猿丷  阅读(615)  评论(0编辑  收藏  举报