利用Aspose.Words将制作好的模板,输出出来自己所需的文件
/// <summary> /// 打印信息和列表 /// </summary> /// <param name="dtinfo"></param> /// <param name="dtlist"></param> public void Print_InfoList(DataTable dtinfo, Dictionary<string, string> dict, DataTable dtlist, int tableindex) { //Print_InfoList(dtinfo, dict, dtlist, false); Document maindoc = new Document(); Document newdoc = new Document(path); DocumentBuilder builder = new DocumentBuilder(newdoc); newdoc.Range.Replace(WordTabChar + "title" + WordTabChar, title, false, false); if (dtinfo != null) { for (int n = 0; n < dtinfo.Columns.Count; n++) { string fieldname = dtinfo.Columns[n].ColumnName.ToLower(); try { newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, dtinfo.Rows[0][fieldname].ToString(), false, false); } catch { } } } if (dict != null) { foreach (string k in dict.Keys) { newdoc.Range.Replace(WordTabChar + k.ToLower() + WordTabChar, dict[k].ToString(), false, false); } } Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, tableindex, true);//定位第一个table PositionPro pos = new PositionPro(); for (int r = 0; r < dtdoc.Rows.Count; r++) { for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++) { if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#")) { pos.row_start = r; pos.cell_start = c; pos.row_end = r; pos.cell_end = c; } if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#")) { pos.row_end = r; pos.cell_end = c; } } } newdoc.Range.Replace("#START#", "", false, false); newdoc.Range.Replace("#END#", "", false, false); DataTable dt = dtlist; List<string> celltabs = new List<string>(); for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++) { string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("a", ""); celltabs.Add(colname); dtdoc.Rows[pos.row_start].Cells[t].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false); } if (dt.Rows.Count > pos.rownum) { int addrow = dt.Rows.Count - pos.rownum; for (int a = 0; a < addrow; a++) { Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start].Clone(true); dtdoc.Rows.Insert(pos.row_start + 1, newrow); } } for (int m = 0; m < dt.Rows.Count; m++) { for (int n = 0; n < celltabs.Count; n++) { try { builder.MoveToCell(tableindex, pos.row_start + m, pos.cell_start + n, 0); builder.Write(dt.Rows[m][celltabs[n].ToString()].ToString()); } catch { } } } maindoc = newdoc; maindoc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认 this.SaveDocument(maindoc); }
//输出文件
private void SaveDocument(Document doc) { SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc"); doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop); }