Aspose.Words 根据HTML table 生成Word模版,并自动生成书签与域
需要引用 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); }