利用標籤導出Word文檔


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爲實線邊框,二、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爲實線邊框,二、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 }

簡單的使用例子:ide

一、先建好Word文檔,設置好排版、插入標籤字體

二、代碼以下:ui

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, "提示"); 
       }
        }
相關文章
相關標籤/搜索