引言:這段時間有項目要用到c#生成Word文檔,通過網絡查找到很多內容,但是功能上滿足不了個人需求,於是決定借助網友們已經寫好的代碼,加以修改完善,以便於更好的交流和以後相似問題可以迅速的解決!
備注:本文用到的相關文件,在日志結尾提供下載
注意:此處要查找的“Microsoft.Office.Interop.Word.dll”版本必須為“11.*.*.*”,“*”代表數字
按照個人編程習慣,先編寫又滿足程序功能需求的詳細的類,在主程序中通過調用這個類的方法實現功能。(一次編寫多次實現)
我把這個類定義為Report,下面是我用到的Report類代碼,僅供參考,並沒有詳盡的備注和錯誤處理,若是您直接使用我的代碼,出現的問題可以恢復本日志或者Q我,空間有我的聯系方式:
word類using System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.Word; namespace TravelAgencyApplication // 根據自己需要修改命名空間 { class Report { private _Application wordApp = null; private _Document wordDoc = null; public _Application Application { get { return wordApp; } set { wordApp = value; } } public _Document Document { get { return wordDoc; } set { wordDoc = value; } } // 通過模板創建新文檔 public void CreateNewDocument(string filePath) { try { killWinWordProcess(); wordApp = new ApplicationClass(); wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApp.Visible = false; object missing = System.Reflection.Missing.Value; object templateName = filePath; wordDoc = wordApp.Documents.Open(ref templateName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } // 保存新文件 public void SaveDocument(string filePath) { object fileName = filePath; object format = WdSaveFormat.wdFormatDocument;//保存格式 object miss = System.Reflection.Missing.Value; wordDoc.SaveAs(ref fileName, 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對象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); } // 在書簽處插入值 public bool InsertValue(string bookmark, string value) { object bkObj = bookmark; if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark)) { wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select(); wordApp.Selection.TypeText(value); return true; } return false; } // 插入表格,bookmark書簽 public Table InsertTable(string bookmark, int rows, int columns, float width) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss); //設置表的格式 newTable.Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以後的數字沒試過) newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度 if (width != 0) { newTable.PreferredWidth = width;//表格寬度 } newTable.AllowPageBreaks = false; return newTable; } // 合並單元格 表id,開始行號,開始列號,結束行號,結束列號 public void MergeCell(int n, int row1, int column1, int row2, int column2) { wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2)); } // 合並單元格 表名,開始行號,開始列號,結束行號,結束列號 public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2) { table.Cell(row1, column1).Merge(table.Cell(row2, column2)); } // 設置表格內容對齊方式 Align水平方向,Vertical垂直方向(左對齊,居中對齊,右對齊分別對應Align和Vertical的值為-1,0,1)Microsoft.Office.Interop.Word.Table table public void SetParagraph_Table(int n, int Align, int Vertical) { switch (Align) { case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對齊 case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對齊 } switch (Vertical) { case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對齊 case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對齊 } } // 設置單元格內容對齊方式 public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical) { switch (Align) { case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對齊 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對齊 } switch (Vertical) { case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對齊 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對齊 } } // 設置表格字體 public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size) { if (size != 0) { table.Range.Font.Size = Convert.ToSingle(size); } if (fontName != "") { table.Range.Font.Name = fontName; } } // 設置單元格字體 public void SetFont_Table(int n, int row, int column, string fontName, double size,int bold) { if (size != 0) { wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size); } if (fontName != "") { wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName; } wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗體,其他值都是 } // 是否使用邊框,n表格的序號,use是或否 // 該處邊框參數可以用int代替bool可以讓方法更全面 // 具體值方法中介紹 public void UseBorder(int n,bool use) { if (use) { wordDoc.Content.Tables[n].Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以後的數字沒試過) } else { wordDoc.Content.Tables[n].Borders.Enable = 0; } } // 給表格插入一行,n表格的序號從1開始記 public void AddRow(int n) { object miss = System.Reflection.Missing.Value; wordDoc.Content.Tables[n].Rows.Add(ref miss); } // 給表格添加一行 public void AddRow(Microsoft.Office.Interop.Word.Table table) { object miss = System.Reflection.Missing.Value; table.Rows.Add(ref miss); } // 給表格插入rows行,n為表格的序號 public void AddRow(int n, int rows) { object miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; for (int i = 0; i < rows; i++) { table.Rows.Add(ref miss); } } // 刪除表格第rows行,n為表格的序號 public void DeleteRow(int n, int row) { Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; table.Rows[row].Delete(); } // 給表格中單元格插入元素,table所在表格,row行號,column列號,value插入的元素 public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value) { table.Cell(row, column).Range.Text = value; } // 給表格中單元格插入元素,n表格的序號從1開始記,row行號,column列號,value插入的元素 public void InsertCell(int n, int row, int column, string value) { wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value; } // 給表格插入一行數據,n為表格的序號,row行號,columns列數,values插入的值 public void InsertCell(int n, int row, int columns, string[] values) { Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; for (int i = 0; i < columns; i++) { table.Cell(row, i + 1).Range.Text = values[i]; } } // 插入圖片 public void InsertPicture(string bookmark, string picturePath, float width, float hight) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; Object linkToFile = false; //圖片是否為外部鏈接 Object saveWithDocument = true; //圖片是否隨文檔一起保存 object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置 wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //設置圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //設置圖片高度 } // 插入一段文字,text為文字內容 public void InsertText(string bookmark, string text) { object oStart = bookmark; object range = wordDoc.Bookmarks.get_Item(ref oStart).Range; Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range); wp.Format.SpaceBefore = 6; wp.Range.Text = text; wp.Format.SpaceAfter = 24; wp.Range.InsertParagraphAfter(); wordDoc.Paragraphs.Last.Range.Text = "\n"; } // 殺掉winword.exe進程 public void killWinWordProcess() { System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD"); foreach (System.Diagnostics.Process process in processes) { bool b = process.MainWindowTitle == ""; if (process.MainWindowTitle == "") { process.Kill(); } } } } }
我在項目中的具體調用的片段代碼:
調用Report report = new Report(); report.CreateNewDocument(Application.StartupPath + "\\地接社.doc"); //模板路徑 report.InsertValue("djs_name", this.comboBox_djs_name.Text); report.InsertValue("djs_man", this.comboBox_djs_man.Text); report.InsertValue("djs_num", this.textBox_djs_num.Text); report.InsertValue("djs_tel", this.textBox_djs_tel.Text); report.InsertValue("djs_fax", this.textBox_djs_fax.Text); report.InsertValue("zts_name", this.comboBox_zts_name.Text); report.InsertValue("zts_man", this.comboBox_zts_man.Text); report.InsertValue("zts_num", this.textBox_zts_num.Text); report.InsertValue("zts_tel", this.textBox_zts_tel.Text); report.InsertValue("zts_fax", this.textBox_zts_fax.Text); report.InsertValue("行程", this.textBoxXC.Text); int xx = Int32.Parse(this.comboBoxdays.Text); report.AddRow(1, xx); for (int i = 0; i < xx;i++ ) { string sss=""; if (up[i].checkBoxZ.Checked||up[i].checkBoxSDZ.Checked||up[i].checkBoxHZ.Checked) sss += "早"; if (up[i].checkBoxZH.Checked||up[i].checkBoxSDZH.Checked||up[i].checkBoxSDZHB.Checked) sss += "中"; if (up[i].checkBoxW.Checked||up[i].checkBoxSDW.Checked) sss += "晚"; string bzz = ""; if (up[i].textBoxS.Text.Trim() == "早餐後,") { } else { bzz += up[i].textBoxS.Text; } if (up[i].textBoxX.Text.Trim() == "午餐後,") { } else { bzz += up[i].textBoxX.Text; } string rq = ""; if (!this.cbb.Checked) rq = up[i].labelDayNo.Text + "\n" + up[i].dateTimePicker.Text + "\n" + up[i].labelWeek.Text; else rq = up[i].labelDayNo.Text; string[] values ={ rq,bzz,sss, up[i].comboBoxAdd.Text}; report.InsertCell(1, 7+i, 4, values); } int deletei = 0 ; for (int i = xx-1; i >=0; i--) { if (up[i].textBoxS.Text.Trim() == "早餐後," && up[i].textBoxX.Text.Trim() == "午餐後,") { report.DeleteRow(1, i + 7); deletei++; } } xx = xx - deletei; report.AddRow(1,1); report.MergeCell(1, 7 + xx, 3, 7 + xx, 4); //合並單元格 表名,開始行號,開始列號,結束行號,結束列號 string[] values1 ={"項 目","分 項 報 價","小計"}; report.InsertCell(1, 7 + xx, 3, values1); report.AddRow(1, 9); string[] sd1 = { "門 票", this.textBoxMP.Text, this.textBoxMPF.Text +"元/人 " }; string[] sd2 = { "住 宿", this.comboBox_zs_bz.Text + " " + this.textBoxZSAJ.Text, this.textBoxZSF.Text+"元/人 " }; string[] sd00 = { "住 宿備 注", this.textBox10.Text}; string[] sd3 = { "餐 費", this.textBoxCF.Text, this.textBoxCFZ.Text+"元/人 " }; string[] sd4 = { "車 費", this.comboBoxCF.Text, this.textBoxCFJG.Text+"元/輛 " }; string[] sd5 = { "火 車", this.textBox3.Text, this.textBox4.Text+"元/人 " }; string[] sd6 = { "導 服", this.textBoxD.Text, this.textBoxDF.Text + "元/團 " }; string[] sd12 = { "陪 同住 宿", this.textBoxPS.Text, this.textBox5.Text + "元/團 " }; report.InsertCell(1, 8 + xx, 3, sd1); report.InsertCell(1, 9 + xx, 3, sd2); report.MergeCell(1, 10 + xx, 2, 10 + xx, 3); report.InsertCell(1, 10 + xx, 2, sd00); report.InsertCell(1, 11 + xx, 3, sd3); report.InsertCell(1, 12 + xx, 3, sd4); report.InsertCell(1, 13 + xx, 3, sd5); report.InsertCell(1, 14 + xx, 3, sd6); report.InsertCell(1, 15 + xx, 3, sd12); report.MergeCell(1, 16 + xx, 2, 16 + xx, 3); //表名,開始行號,開始列號,結束行號,結束列號 report.AddRow(1, 3); string[] sd7 = { "合 計", this.textBoxHJ.Text }; string[] sd9 = { "自 理項 目", this.textBoxZFXM.Text }; string[] sd10 = { "購 物點", this.textBoxGWD.Text }; string[] sd11 = { "備 注", this.textBox7.Text }; report.InsertCell(1, 16 + xx, 2, sd7); report.InsertCell(1, 17 + xx, 2, sd9); report.InsertCell(1, 18 + xx, 2, sd10); report.InsertCell(1, 19 + xx, 2, sd11); report.UseBorder(1,iss); report.SetParagraph_Table(1, 16 + xx, 2, -1, 0); report.SetParagraph_Table(1, 17 + xx, 2, -1, 0); report.SetParagraph_Table(1, 18 + xx, 2, -1, 0); report.SetParagraph_Table(1, 19 + xx, 2, -1, 0); report.SetParagraph_Table(1, 10 + xx, 2, -1, 0); report.SetFont_Table(1, 16 + xx, 1, "宋體", 14,1); report.SetFont_Table(1, 17 + xx, 1, "宋體", 14,1); report.SetFont_Table(1, 18 + xx, 1, "宋體", 14,1); report.SetFont_Table(1, 19 + xx, 1, "宋體", 14,1); report.SetFont_Table(1, 16 + xx, 2, "宋體", 12,1); report.SetFont_Table(1, 7 + xx, 1, "宋體", 14, 1); report.SetFont_Table(1, 7 + xx, 2, "宋體", 14, 1); report.SetFont_Table(1, 7 + xx, 3, "宋體", 14, 1); report.SetParagraph_Table(1, 7 + xx, 2, 0, 0); report.SaveDocument(file);
我是使用一半模板一般代碼的方式導出的:
直接上圖:
相關文件下載:
1.Microsoft.Office.Interop.Word多版本壓縮包