原文出處:https://www.cnblogs.com/ilefei/p/3508463.html
一:模板的創建 (注意文件后綴只能是.docx或.doct)
在需要位置 插入-文檔部件-域,
域名:MacroButton
宏名:DoFieldClick
顯示文字:這個自己設置,為了與模板其他文字區分,可以用"[]"括起來.
需要多少替換內容,添加多少域即可.
二:添加項目
在解決方案中添加項目WordMLHelper,在原項目中添加對WordMLHelper的引用后可以直接調用.(見頭部出處)
三:調用方法
首先確定模板文件位置和導出文件的生成路徑.
private string mubanFile = "muban.docx"; private string outputPath = @"test1.docx";
string templatePath = System.Web.HttpContext.Current.Request.MapPath(mubanFile );
//mvc讀取文件路徑跟原文出處不一樣
List<TagInfo> tagInfos = wordMLHelper.GetAllTagInfo(System.IO.File.OpenRead(templatePath));//打開模板文件,獲取所有填充域 for (int i = 0; i < tagInfos.Count; i++) { //填充域有兩種類型,1:段落或圖片,2:表格 //對填充域填充時需先判斷填充域類型 if (tagInfos[i].Tbl == null) { if (string.Equals(tagInfos[i].TagTips.Trim(), "[NO]")) { TxtInfo txtInfo = new TxtInfo(); txtInfo.Content = info.NO;////////NO;--info實體類 txtInfo.ForeColor = "000000"; txtInfo.Size = 32; txtInfo.HightLight = HighlightColor.None; txtInfo.underlineStyle = UnderlineStyle.Single; tagInfos[i].AddContent(txtInfo); } } else { TableStructureInfo tblInfo = tagInfos[i].Tbl; if (tagInfos[i].Seq == 2)//整個表格創建 { for (int j = 0; j < 3; j++) { RowStructureInfo row = new RowStructureInfo(); for (int k = 0; k < 3; k++) { CellStructureInfo cell = new CellStructureInfo(); TxtInfo txtInfo = new TxtInfo(); txtInfo.Content = "第" + (j + 1) + "行,第" + (k + 1) + "列"; txtInfo.Size = 25; txtInfo.ForeColor = "0000ff"; cell.AddContentLine(txtInfo); row.AddCell(cell); } tblInfo.AddRow(row); } } } } if (!string.IsNullOrEmpty(saveFile)) { templatePath = System.Web.HttpContext.Current.Request.MapPath(tempFile); wordMLHelper.GenerateWordDocument(System.IO.File.OpenRead(templatePath) , System.Web.HttpContext.Current.Request.MapPath(saveFile) , tagInfos); Assistance.RemoveAllTmpFile();// 刪除所有臨時文件 //Response.Redirect(Request.Url.AbsoluteUri); }
四、導出結果文檔如果原來有下滑線,則在引用的項目中添加枚舉類(在HighlightColor枚舉下添加)
public enum UnderlineStyle { Single=0, Words, Double, Thick, Dotted, DottedHeavy, Dash, DashedHeavy, DashLong, DashLongHeavy, DotDash, DashDotHeavy, DotDotDash, DashDotDotHeavy, Wave, WavyHeavy, WavyDouble, None, }
添加下滑線枚舉變量(在TxtInfo類中)
public UnderlineStyle underlineStyle = UnderlineStyle.None;
在WordMLHelper類中的AssembleTxtRun方法中添加判斷:
if (txtInfo.underlineStyle!=UnderlineStyle.None) { Underline underline = new Underline(); underline.Val = (UnderlineValues)((int)txtInfo.underlineStyle); rPr.AppendChild(underline); } txtRun.AppendChild(rPr);//在上面插入下滑線的判斷
其他內容參照原出處
對word已有表格更新操作:
if (tagInfos[i].Seq == 0) { TxtInfo txtInfo; var cell2 = tblInfo.Rows[2].Cells[1];//通過表格索引修改,word文檔不需要操作,注意:word中不能含相同名稱否則會報索引大小錯誤
,同名可通過修改word中的同名文字然后用代碼替換回來 txtInfo = new TxtInfo(); txtInfo.Content = newRow["RecordType1"].ToString();//////// cell121.AddContentLine(new TxtInfo() { Content = "" }); cell121.AddContentLine(new TxtInfo() { Content = "☑ A", Size = 24 }); cell121.AddContentLine(new TxtInfo() { Content = "☐ B", Size = 24 }); cell121.AddContentLine(new TxtInfo() { Content = "☐ C", Size = 24 }); } }