需要引用 Aspose.Words 請自行下載
先准備一個HTML 文件,文件內容參考下面
<table border="1" cellspacing="0" style="margin: 0 auto; width: 90%; border-color: #000; text-align: center;" class="layui-table"> <colgroup> <col style="width: 20%; text-align: center; vertical-align: middle"> <col style="width: 20%;"> <col style="width: 20%;"> <col style="width: 20%;"> <col style="width: 20%;"> </colgroup> <tbody> <tr> <td rowspan="6"><span>申請單位基本情況</span></td> <td><span>項目申報單位</span></td> <td colspan="3"> <input type="text" name="4000" id="4000" class="layui-input"> </td> </tr> <tr> <td><span>單位地址</span></td> <td colspan="3"> <input type="text" name="4001" id="4001" class="layui-input"> </td> </tr> <tr> <td><span>注冊資本(萬元)</span></td> <td> <input type="text" name="4002" id="4002" class="layui-input"></td> <td><span>企業社會信用代碼</span></td> <td> <input type="text" name="4003" id="4003" class="layui-input"> </td> </tr> <tr> <td><span>對外貿易經營者備案表編號</span></td> <td> <input type="text" name="4004" id="4004" class="layui-input"> </td> <td> <input type="text" name="4005" id="4005" class="layui-input" style="width: 50px; display: inline-block"> <span>年出口額</span><span>(萬美元)</span></td> <td> <input type="text" name="4006" id="4006" class="layui-input"> </td> </tr> <tr> <td> <span>法定代表人</span></td> <td> <input type="text" name="4007" id="4007" class="layui-input"> </td> <td><span>聯系電話(手機)</span></td> <td> <input type="text" name="4008" id="4008" class="layui-input"> </td> </tr> <tr> <td><span>聯 系 人</span></td> <td> <input type="text" name="4009" id="4009" class="layui-input"> </td> <td><span>聯系電話(手機)</span></td> <td> <input type="text" name="4010" id="4010" class="layui-input"> </td> </tr> <tr> <td rowspan="2"><span>上一年企業基本情況</span></td> <td><span>企業總資產(萬元)</span></td> <td> <input type="text" name="4011" id="4011" class="layui-input"> </td> <td><span>營業收入(萬元)</span></td> <td> <input type="text" name="4012" id="4012" class="layui-input"> </td> </tr> <tr> <td><span>入庫稅金(萬元)</span></td> <td> <input type="text" name="4013" id="4013" class="layui-input"> </td> <td><span>財政補助(萬元)</span></td> <td> <input type="text" name="4014" id="4014" class="layui-input"> </td> </tr> <tr> <td rowspan="9"><span>項目基本情況</span></td> <td><span>項目類別</span></td> <td> <select name="4015" id="4015"> <option value="類別一">類別一</option> <option value="類別二">類別二</option> <option value="類別三">類別三</option> </select> </td> <td></td> <td></td> </tr> <tr> <td><span>項目名稱</span></td> <td colspan="3"> <input type="text" name="4016" id="4016" class="layui-input"> </td> </tr> <tr> <td><span>投保保險公司名稱</span></td> <td colspan="3"> <input type="text" name="4017" id="4017" class="layui-input"> </td> </tr> <tr> <td><span>投保國家及地區</span></td> <td colspan="3"> <input type="text" name="4018" id="4018" class="layui-input"> </td> </tr> <tr> <td><span>投保金額(萬元)</span></td> <td> <input type="text" name="4019" id="4019" class="layui-input"> </td> <td><span>申請補助(萬元)</span></td> <td> <input type="text" name="4020" id="4020" class="layui-input"> </td> </tr> <tr> <td><span>貨物出險金額(萬美元)</span></td> <td> <input type="text" name="4021" id="4021" class="layui-input"> </td> <td><span>賠付金額(萬元)</span></td> <td> <input type="text" name="4022" id="4022" class="layui-input"> </td> </tr> <tr> <td><span>項目所屬區</span></td> <td> <select name="4023" id="4023"> <option value="西湖區">西湖區</option> <option value="上城區">上城區</option> <option value="下城區">下城區</option> </select> </td> <td colspan="2"></td> </tr> <tr> <td rowspan="2"><span>附件</span></td> <td><span>申報材料(必須提供)</span></td> <td valign="top" colspan="2"><span></span></td> </tr> <tr> <td><span>其他申報證明材料</span></td> <td valign="top" colspan="2"></td> </tr> </tbody> </table>
然后后台讀取這個HTML
/// <summary> /// 按照HTML生成WORD模版 /// 輸入框Input,選擇框Select都替換為 域 /// </summary> protected void CreateWordSetFiled() { string sp = Server.MapPath(_savePath); if (!System.IO.Directory.Exists(sp)) { System.IO.Directory.CreateDirectory(sp); } _templateHtmlPath = Server.MapPath(_templateHtmlPath);//HTML文件路徑 string f = Guid.NewGuid().ToString("N") + ".doc"; string copyto = sp + f;//生成文件的保存地址 //讀取HTML using (StreamReader reader = new StreamReader(_templateHtmlPath)) { string html = reader.ReadToEnd(); List<string> list = new List<string>(); html = html.Replace("\r\n", ""); html = ReplaceHtml(html, ref list);//處理HTML Aspose.Words.Document wordDoc = new Aspose.Words.Document(); DocumentBuilder builder = new DocumentBuilder(wordDoc); builder.InsertHtml(html); //獲取Table 並循環行與列 NodeCollection allTables = wordDoc.GetChildNodes(NodeType.Table, true); for (int t = 0; t < allTables.Count; t++) { Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)allTables[t]; NodeCollection rows = table.GetChildNodes(NodeType.Row, true); for (int r = 0; r < rows.Count; r++) { NodeCollection cell = ((Row)rows[r]).GetChildNodes(NodeType.Cell, true); for (int c = 0; c < cell.Count; c++) { foreach (string s in list) { if (cell[c].ToString(SaveFormat.Text).Trim().StartsWith(s)) { builder.MoveToCell(t, r, c, 0); Aspose.Words.Replacing.FindReplaceOptions opt = new Aspose.Words.Replacing.FindReplaceOptions(); cell[c].Range.Replace(s, "", opt);//清除文本 string fl = string.Format(" MERGEFIELD {0} ", s); builder.InsertField(fl);//插入域 /* builder.StartBookmark(s); //插入書簽 builder.Write(s); builder.EndBookmark(s); * */ } } } } } //wordDoc.MailMerge.DeleteFields(); //清空域 wordDoc.Range.Bookmarks.Clear(); //清空書簽 wordDoc.Save(copyto, SaveFormat.Doc); } } /// <summary> /// 將HTML里的 控件 換成 標簽,並返回替換好的HTML /// </summary> /// <param name="html"></param> /// <param name="list"></param> /// <returns></returns> protected string ReplaceHtml(string html,ref List<string> list) { MatchCollection mc = Regex.Matches(html, "<input?\\s+.*?id=[\"']?([^\"'\\s>]+)[\"']?[^>]*>"); MatchCollection mc2 = Regex.Matches(html, "<select?\\s+.*?id=[\"']?([^\"'\\s>]+)[\"']?[^>]*>.*?</select>"); foreach (Match m in mc) { html = html.Replace(m.Value, "s" + m.Groups[1].Value); list.Add("s" + m.Groups[1].Value); } foreach (Match m in mc2) { html = html.Replace(m.Value, "s" + m.Groups[1].Value); list.Add("s" + m.Groups[1].Value); } return html; }
生成模版后,可以接收第一個HTML提交的數據,並寫入WORD模版中
protected void Save2() { string json = Request["json"]; DataTable dt = GetData(json); string sp = Server.MapPath(_savePath); if (!System.IO.Directory.Exists(sp)) { System.IO.Directory.CreateDirectory(sp); } _templatePath = Server.MapPath(_templatePath); string f = Guid.NewGuid().ToString("N") + ".pdf"; string copyto = sp + f; File.Copy(_templatePath.ToString(), copyto, true); //將文件復制到結果文檔中 Aspose.Words.Document doc = new Aspose.Words.Document(copyto); Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc); foreach (DataColumn c in dt.Columns) { string field = string.Format("s{0}", c.ColumnName); while (builder.MoveToMergeField(field)) { builder.Write(dt.Rows[0][c.ColumnName].ToString()); } } /* string error = string.Empty; List<string> list = GetFileds(doc, out error); foreach (string s in list) { while (builder.MoveToMergeField(s)) { builder.Write(""); } } * */ doc.MailMerge.DeleteFields(); //清空未使用的域 doc.Save(copyto, Aspose.Words.SaveFormat.Pdf); //MemoryStream docStream = new MemoryStream(); //doc.Save(docStream, Aspose.Words.SaveFormat.Pdf); //Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(docStream); //pdfDocument.Save(docStream); /* Response.ContentType = "application/msword"; Response.AddHeader("content-disposition", "attachment; filename=" + info.itemname + ".pdf"); Response.BinaryWrite(docStream.ToArray()); Response.End(); * */ } protected DataTable GetData(string json) { //Newtonsoft.Json.Linq.JArray array = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as JArray; JObject objdata = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json); StringBuilder columns = new StringBuilder(); DataTable table = new DataTable(); JObject objColumns = objdata;// array[0] as JObject; //構造表頭 foreach (JToken jkon in objColumns.AsEnumerable<JToken>()) { string name = ((JProperty)(jkon)).Name; columns.Append(name + ","); table.Columns.Add(name); } DataRow row = table.NewRow(); JObject obj = objdata; foreach (JToken jkon in obj.AsEnumerable<JToken>()) { string name = ((JProperty)(jkon)).Name; string value = ((JProperty)(jkon)).Value.ToString(); row[name] = value; } table.Rows.Add(row); return table; }
使用書簽
//使用書簽替換 protected void Save() { string json = Request["json"]; DataTable dt = GetData(json); string sp = Server.MapPath(_savePath); if (!System.IO.Directory.Exists(sp)) { System.IO.Directory.CreateDirectory(sp); } _templatePath = Server.MapPath(_templatePath); string f = Guid.NewGuid().ToString("N") + ".doc"; string copyto = sp + f; File.Copy(_templatePath.ToString(), copyto, true); //將文件復制到結果文檔中 Aspose.Words.Document doc = new Aspose.Words.Document(copyto); Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc); foreach (Bookmark bm in doc.Range.Bookmarks) { if (dt.Columns.Contains(bm.Name.TrimStart('s'))) { builder.MoveToBookmark(bm.Name); bm.Text = dt.Rows[0][bm.Name.TrimStart('s')].ToString(); } } doc.Save(copyto, Aspose.Words.SaveFormat.Doc); }