1)當然可以考慮使用aspose.word。使用書簽替換的方案替換模板中對應的書簽值。
2)但是我使用了Interop.Word,下面記錄使用類及要注意的地方
3)使用類
Report.cs 來自於網上 修改了在添加表格時焦點移動到最后並新建一頁
using System; using System.Collections.Generic; using System.Text; using Microsoft.Office.Interop.Word; namespace Song_Public //這邊需要換成自己的命名空間名 { public 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) { 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); } //保存新文件 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;//表格插入位置 // Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 // wordApp.Selection.EndKey(6, 0); wordApp.Selection.EndKey(WdUnits.wdStory); wordApp.Selection.InsertNewPage(); //object start = 0; //object end = 0; //Range tableLocation = wordDoc.Range(ref start, ref end); Table newTable = wordDoc.Tables.Add(wordApp.Selection.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; //object oMissing = System.Reflection.Missing.Value; //wordApp.Visible = true; //wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //object start = 0; //object end = 0; //Microsoft.Office.Interop.Word.Range tableLocation = wordDoc.Range(ref start, ref end); //Table newTable = wordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing); return newTable; } /// <summary> /// 添加一個新表 參考 /// </summary> public Table AddTable(int rows, int columns) { object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible = true; WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); Table newTable = WordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing);//3行4列的表 //設置表的格式 newTable.Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以后的數字沒試過) newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度 newTable.AllowPageBreaks = false; return newTable; } //合並單元格 表名,開始行號,開始列號,結束行號,結束列號 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) public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, 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;//底端對齊 } } //設置表格字體 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; } } //是否使用邊框,n表格的序號,use是或否 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 = 2; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以后的數字沒試過) } } //給表格插入一行,n表格的序號從1開始記 public void AddRow(int n) { object miss = System.Reflection.Missing.Value; wordDoc.Content.Tables[n].Rows.Add(ref miss); wordDoc.Content.Tables[n].Rows.Height = 100;//設置新增加的這行表格的高度 } //給表格添加一行 public void AddRow(Microsoft.Office.Interop.Word.Table table) { object miss = System.Reflection.Missing.Value; table.Rows.Height = 40; 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); } } //給表格中單元格插入元素,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(); } } } } }
4)使用方式
1)按書簽導入值 書簽設置見下方
Report report = new Report(); var path = System.Web.HttpContext.Current.Server.MapPath("/files/word/2.doc"); var savapath = System.Web.HttpContext.Current.Server.MapPath("/files/word/" + RandomStr.GetSerialNumber(4) + ".doc"); report.CreateNewDocument(path); //模板路徑 report.InsertValue("name", "世界杯");//在書簽“name”處插入值
2)導入表格
Table table2 = report.InsertTable("table2", 4, 4, 0); //在書簽“table2”處插入2行3列行寬
3)導入表格數據
report.InsertCell(table2, 1, 1, "項目名稱");//表名,行號,列號,值
4)合並單元格
report.MergeCell(table2, 1, 2, 1, 4); //表名,開始行號,開始列號,結束行號,結束列號
5)設置字體大小
report.SetFont_Table(table2, "宋體", 11);//宋體14磅
6)文檔保存
report.SaveDocument(savapath);
7)類中可修改的叮當
table.Rows.Height = 40; //添加行時可 修改當前行的高度AddRow方法
//InsertTable方法修改回按書簽的位置來添加表格 此方法不適用多個表格的導出
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; }
wordApp.Selection.EndKey(WdUnits.wdStory);//焦點放到文檔最后
5)注意點
1)表格導出時會嵌套表
原因 :表格導入完成后 焦點的位置默認會在表格里 在次插入會導致在表格內嵌套
解決:把焦點放到文檔末尾 wordApp.Selection.EndKey(WdUnits.wdStory);
2)合並時會報所要求的的成員不存在
原因:這個錯誤的原因就是沒有找到單元格,會有幾種情況1)沒有代碼中定義的書簽,2)表格前一項合並完 多列合成一列 后面再用之前的列值來合並。肯定找不到
解決:先輸出對應的列與值,最后在處理合並。每次合並都記錄,當前行的合並列數 如下
//處理合並 var pans = 0;//合並數 foreach (var o in lo) //lo為一個list<other> { report.MergeCell(table2, o.row, o.col1-pans, o.row, o.col2- pans); pans++; }
3)書簽的插入
word->插入->書簽->輸入書簽名稱->添加
4)檢索 COM 類工廠中 CLSID 為 {000209FF-0000-0000-C000-000000000046} 的組件失敗,原因是出現以下錯誤: 80070005 拒絕訪問
原因:沒有權限讀取word.dll
解決:http://blog.csdn.net/ououou123456789/article/details/6102036
5)ApplicationClass() 不被識別