private void CreateTableOnPdfFile_3() { //create filename of pdf_file_tosave var word_file_tosave = @"d:\1.docx"; //new pdf doc var word_doc = new Aspose.Words.Document(); var table1 = new Aspose.Words.Tables.Table(word_doc); var row1 = new Aspose.Words.Tables.Row(word_doc); var cell1 = new Aspose.Words.Tables.Cell(word_doc); //var para1 = new Aspose.Words.Paragraph(word_doc); cell1.AppendChild(new Aspose.Words.Paragraph(word_doc)); cell1.FirstParagraph.AppendChild(new Aspose.Words.Run(word_doc, "1223333")); row1.AppendChild(cell1); table1.AppendChild(row1); word_doc.FirstSection.Body.AppendChild(table1); //save try { word_doc.Save(word_file_tosave, Aspose.Words.SaveFormat.Docx); MessageBox.Show("Save Successfully!"); //pdfDoc.Dispose(); Process.Start(word_file_tosave); } catch { MessageBox.Show("Faild to Save!"); } }
/// <summary> /// 插入表格 /// </summary> /// <param name="dt"></param> /// <param name="oWordApplic"></param> /// <param name="haveBorder"></param> public static void InsertTable(DataTable dt, DocumentBuilder oWordApplic, bool haveBorder) { Aspose.Words.Tables.Table table = oWordApplic.StartTable();//开始画Table ParagraphAlignment paragraphAlignmentValue = oWordApplic.ParagraphFormat.Alignment; oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center; //列头 foreach (DataColumn col in dt.Columns) { oWordApplic.InsertCell(); oWordApplic.Font.Size = 8; oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐 if (haveBorder == true) { //设置外框样式 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single; //样式设置结束 } oWordApplic.Write(col.ColumnName); } oWordApplic.EndRow(); //添加Word表格 for (int row = 0; row < dt.Rows.Count; row++) { //oWordApplic.RowFormat.Height = 25; for (int col = 0; col < dt.Columns.Count; col++) { oWordApplic.InsertCell(); oWordApplic.Font.Size = 8; //oWordApplic.Font.Name = "宋体"; //oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐 //oWordApplic.CellFormat.Width = 50.0; //oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50); if (haveBorder == true) { //设置外框样式 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single; //样式设置结束 } oWordApplic.Write(dt.Rows[row][col].ToString()); } oWordApplic.EndRow(); } oWordApplic.EndTable(); oWordApplic.ParagraphFormat.Alignment = paragraphAlignmentValue; //table.Alignment = Aspose.Words.Tables.TableAlignment.Center; //table.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto; }
public bool InsertTable(System.Data.DataTable dt, bool haveBorder) { Aspose.Words.Tables.Table table = oWordApplic.StartTable();//开始画Table ParagraphAlignment paragraphAlignmentValue = oWordApplic.ParagraphFormat.Alignment; oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center; //添加Word表格 for (int row = 0; row < dt.Rows.Count; row++) { oWordApplic.RowFormat.Height = 25; for (int col = 0; col < dt.Columns.Count; col++) { oWordApplic.InsertCell(); oWordApplic.Font.Size = 10.5; oWordApplic.Font.Name = "宋体"; oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; //垂直居中对齐 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center; //水平居中对齐 oWordApplic.CellFormat.Width = 50.0; oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50); if (haveBorder == true) { //设置外框样式 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single; //样式设置结束 } oWordApplic.Write(dt.Rows[row][col].ToString()); } oWordApplic.EndRow(); } oWordApplic.EndTable(); oWordApplic.ParagraphFormat.Alignment = paragraphAlignmentValue; table.Alignment = Aspose.Words.Tables.TableAlignment.Center; table.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto; return(true); }
/// <summary> /// 获得单元格的内容对象 /// </summary> /// <param name="table"></param> /// <param name="txt"></param> /// <returns></returns> public Paragraph GetCellContentObj(Aspose.Words.Tables.Table table, string txt) { Aspose.Words.Paragraph p = new Paragraph(table.Document); p.AppendChild(new Run(table.Document, txt)); return(p); }
public static string Process(DocOptions options) { string result = ""; try { var config = ConfigHelpers.GetDefaultConfig(options.Config); IDatabase database = new Database(config, LogHelpers.LogStatic, option => { //option.CodeGenProjectName = projectName; //option.CodeGenNameSpace = nameSpace; //option.CodeGenTableFilter = tablePrefixFilter; //option.AutoMigrateOnContainTable = onlyTable; }); string type = options.Type; var projectConfig = DbLoader.ConvertDatabaseConfigToProjectConfig(database); LogHelpers.LogStatic(projectConfig.ToString()); string msg = ""; var tables = DbLoader.GetTableInfos(database, projectConfig, null, null, out msg); LogHelpers.LogStatic(msg); string docName = projectConfig.DatabaseName; OutputContext _OutputContext = new OutputContext(); _OutputContext.Tables = tables; // context.Mappers = mapperDict; _OutputContext.ProjectConfig = projectConfig; //context.ParserConfig = _parseConfig; string FileName = docName + "数据库设计文档." + type; string RealOutputFileName = System.IO.Path.Combine(DbLoader.GetProjectDirectory(projectConfig), FileName); if (type == "html") { string templatePath = DbLoader.MapPath("~/DocGen/dicthtml.cshtml"); if (System.IO.File.Exists(templatePath)) { string tempalteContent = FileHelper.ReadFile(templatePath); string key = "exportdicthtml"; var templateEngine = DbLoader.CreateTemplateEngine(); var generateResult = templateEngine.Parse <OutputContext>(tempalteContent, key, _OutputContext); string content = generateResult; templateEngine.OutputResult(RealOutputFileName, content); //return File(RealOutputFileName, "application/zip-x-compressed", FileName); } } else { //Other types string tmppath = DbLoader.MapPath("~/DocGen/dict.dot"); // System.IO.Path.Combine(path, "Template", "template.dot"); Aspose.Words.Document doc = new Aspose.Words.Document(tmppath); //载入模板 Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); string dbName = docName; if (string.IsNullOrEmpty(dbName)) { dbName = _OutputContext.ProjectConfig.Name; } doc.Range.Replace("{$.DBName}", dbName, false, false); Aspose.Words.Tables.Table tabletemp = (Aspose.Words.Tables.Table)doc.GetChild(Aspose.Words.NodeType.Table, 0, true); Aspose.Words.Tables.Table tableClone = (Aspose.Words.Tables.Table)tabletemp.Clone(true); for (int k = 0; k < _OutputContext.Tables.Count; k++) { Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(Aspose.Words.NodeType.Table, k, true); var tb = _OutputContext.Tables[k]; //添加表头标题 var par = table.ParentNode.InsertBefore(new Aspose.Words.Paragraph(doc), table); builder.MoveTo(par); builder.ParagraphFormat.StyleIdentifier = Aspose.Words.StyleIdentifier.Heading1; builder.Font.Size = 11; builder.Write(tb.Comment + "(" + tb.Name + ")"); Aspose.Words.Tables.Cell cellh = table.FirstRow.Cells[1]; cellh.RemoveAllChildren(); builder.MoveToCell(k, 0, 1, 0); builder.Write(tb.Name); Aspose.Words.Tables.Cell cellh3 = table.FirstRow.Cells[3]; cellh3.RemoveAllChildren(); builder.MoveToCell(k, 0, 3, 0); builder.Write(tb.Comment != null ? tb.Comment : ""); for (int i = 0; i < tb.Columns.Count; i++) { for (int j = 0; j < table.LastRow.Cells.Count; j++) { Aspose.Words.Tables.Cell cell = table.LastRow.Cells[j]; cell.RemoveAllChildren(); builder.MoveToCell(k, table.Rows.Count - 1, j, 0); switch (j) { case 0: builder.Write(tb.Columns[i].Comment != null ? tb.Columns[i].Comment : ""); break; case 1: builder.Write(tb.Columns[i].Name); break; case 2: builder.Write(tb.Columns[i].RawType); break; case 3: builder.Write(tb.Columns[i].Length.ToString()); break; case 4: builder.Write(tb.Columns[i].Scale.ToString()); break; case 5: builder.Write(tb.Columns[i].IsPK ? "Y" : ""); break; case 6: builder.Write(tb.Columns[i].IsNullable ? "Y" : ""); break; case 7: builder.Write(tb.Columns[i].IsAutoIncrement ? "Y" : ""); break; case 8: builder.Write(tb.Columns[i].DefaultValue == null ? "" : tb.Columns[i].DefaultValue.ToString()); break; default: break; } } if (i < tb.Columns.Count - 1) { Aspose.Words.Tables.Row clonedRow = (Aspose.Words.Tables.Row)table.LastRow.Clone(true); table.AppendChild(clonedRow); } } if (k < _OutputContext.Tables.Count - 1) { Aspose.Words.Tables.Table tbClone = (Aspose.Words.Tables.Table)tableClone.Clone(true); table.ParentNode.InsertAfter(tbClone, table); } } doc.UpdateFields(); doc.Range.Replace("{$.NowDateTime}", DateTime.Now.ToString(), false, false); Aspose.Words.SaveFormat sformat = Aspose.Words.SaveFormat.Doc; switch (type) { case "doc": sformat = Aspose.Words.SaveFormat.Doc; break; case "docx": sformat = Aspose.Words.SaveFormat.Docx; break; //case "html": // sformat = Aspose.Words.SaveFormat.Html; // break; case "odt": sformat = Aspose.Words.SaveFormat.Odt; break; case "pdf": sformat = Aspose.Words.SaveFormat.Pdf; break; case "png": sformat = Aspose.Words.SaveFormat.Png; break; case "tiff": sformat = Aspose.Words.SaveFormat.Tiff; break; case "text": sformat = Aspose.Words.SaveFormat.Text; break; case "epub": sformat = Aspose.Words.SaveFormat.Epub; break; default: break; } doc.Save(RealOutputFileName, sformat); //return File(RealOutputFileName, "application/zip-x-compressed", FileName); } if (options.Zip) { var zipDir = RealOutputFileName; string zipedName = docName + "-" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"; string zipOutFileName = System.IO.Path.Combine(DbLoader.GetDataDirectory(), zipedName); //ZipHelper.ZipDir(zipDir, zipOutFileName, 9); //ZipHelper.ZipManyFilesOrDictorys(zipDir, zipOutFileName, ""); ZipHelper.ZipFile(zipDir, zipOutFileName); RealOutputFileName = zipOutFileName; } LogHelpers.LogStatic("生成数据库字典成功:" + RealOutputFileName); ConfigHelpers.OpenDir(RealOutputFileName); } catch (Exception ex) { LogHelpers.LogStatic("DocGenerator 生成数据库字典出错!", ex, Pure.Data.MessageType.Error); } return(result); }
private static string sqliteDbLocation = ConfigurationManager.AppSettings["sqliteDBLocation"].ToString(); //数据库存放路径 public static void CreateTable(string bookName, DataTable dt) { try { builder.MoveToBookmark(bookName); //builder.StartTable();//开始画Table Aspose.Words.Tables.Table table = builder.StartTable(); builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; // RowAlignment.Center; string str = string.Empty; builder.RowFormat.Height = 20; //builder.RowFormat.HeightRule = HeightRule.Auto; //添加列头 for (int i = 0; i < dt.Columns.Count; i++) { builder.InsertCell(); //Table单元格边框线样式 builder.CellFormat.Borders.LineStyle = LineStyle.Single; //Table此单元格宽度 builder.CellFormat.Width = 500; //此单元格中内容垂直对齐方式 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; //字体大小 builder.Font.Size = 10; //是否加粗 builder.Bold = true; //向此单元格中添加内容 builder.Write(dt.Columns[i].ColumnName); } builder.EndRow(); //添加每行数据 for (int i = 0; i < dt.Rows.Count; i++) { builder.RowFormat.HeightRule = HeightRule.Auto; for (int j = 0; j < dt.Columns.Count; j++) { str = dt.Rows[i][j].ToString(); //插入Table单元格 builder.InsertCell(); //Table单元格边框线样式 builder.CellFormat.Borders.LineStyle = LineStyle.Single; //Table此单元格宽度 跟随列头宽度 builder.CellFormat.Width = 500; //此单元格中内容垂直对齐方式 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; //字体大小 builder.Font.Size = 10; //是否加粗 builder.Bold = false; //向此单元格中添加内容 builder.Write(str); } //Table行结束 builder.EndRow(); } table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);///设置表格宽度 适应设置的宽度 builder.EndTable(); } catch (Exception ex) { throw new Exception(ex.Message, ex); //addLog("插入表格出现 " + ex.Message); } }
/// <summary> /// 创建表格 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bookName"></param> /// <param name="list"></param> /// <param name="columNames"></param> /// <param name="propNames"></param> public static void CreateTable <T>(string bookName, List <T> list, string[] columNames, string[] propNames) { try { Type tbc = typeof(T); BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; PropertyInfo[] propInfos = tbc.GetProperties(bindingFlags); builder.MoveToBookmark(bookName); builder.StartTable();//开始画Table Aspose.Words.Tables.Table table = builder.StartTable(); builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; // RowAlignment.Center; string str = string.Empty; builder.RowFormat.Height = 20; //builder.RowFormat.HeightRule = HeightRule.Auto; PropertyInfo propertyInfo; //添加列头 for (int i = 0; i < columNames.Length; i++) { builder.InsertCell(); //Table单元格边框线样式 builder.CellFormat.Borders.LineStyle = LineStyle.Single; //Table此单元格宽度 builder.CellFormat.Width = 500; //此单元格中内容垂直对齐方式 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; //字体大小 builder.Font.Size = 10; //是否加粗 builder.Bold = true; //向此单元格中添加内容 //builder.Write(dt.Columns[i].ColumnName); builder.Write(columNames[i]); } builder.EndRow(); object cellV = null; //添加每行数据 for (int i = 0; i < list.Count; i++) { builder.RowFormat.HeightRule = HeightRule.Auto; foreach (string propName in propNames) { propertyInfo = tbc.GetProperty(propName.UpperCaseFirst()); if (propertyInfo != null) { cellV = propertyInfo.GetValue(list[i]); } str = (cellV == null || "".Equals(cellV.ToString())) ? " " : cellV.ToString(); //dt.Rows[i][j].ToString(); //插入Table单元格 builder.InsertCell(); //Table单元格边框线样式 builder.CellFormat.Borders.LineStyle = LineStyle.Single; //Table此单元格宽度 跟随列头宽度 builder.CellFormat.Width = 500; //此单元格中内容垂直对齐方式 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; //字体大小 builder.Font.Size = 10; //是否加粗 builder.Bold = false; //向此单元格中添加内容 builder.Write(str); } //Table行结束 builder.EndRow(); } //table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);///设置表格宽度 适应设置的宽度 builder.EndTable(); } catch (Exception ex) { throw new Exception(ex.Message, ex); // addLog("插入表格出现 " + ex.Message); } }
/// <summary> /// 输出word内容 /// </summary> /// <param name="progressDialog"></param> public static void wordOutput(CircleProgressBarDialog progressDialog) { //判断是否加载了项目信息 PluginRoot pt = PublicReporterLib.PluginLoader.getLocalPluginRoot <PluginRoot>(); if (pt.projectObj == null) { return; } Report(progressDialog, 10, "准备Word...", 1000); //创建word文档 string fileName = pt.projectObj.BianHao + "-合同书.docx"; WordUtility wu = new WordUtility(); wu.createNewDocument(Path.Combine(Path.Combine(pt.RootDir, "Helper"), "template.doc")); try { Report(progressDialog, 20, "准备数据...", 1000); Report(progressDialog, 30, "写入基本信息...", 1000); #region 固定文本替换 wu.insertValue("首页_合同编号", pt.projectObj.HeTongBianHao); wu.insertValue("首页_密级", pt.projectObj.HeTongMiJi); wu.insertValue("首页_密级期限", pt.projectObj.HeTongMiQi.ToString()); wu.insertValue("首页_合同名称", pt.projectObj.HeTongMingCheng); wu.insertValue("首页_承研单位", pt.projectObj.ChengYanDanWeiMingCheng); wu.insertValue("首页_项目负责人", pt.projectObj.HeTongFuZeRen); wu.insertValue("首页_起止时间", pt.projectObj.HeTongKaiShiShiJian.ToString("yyyy年MM月dd日") + " 至" + pt.projectObj.HeTongJieShuShiJian.ToString("yyyy年MM月dd日")); wu.insertValue("基本信息_合同编号", pt.projectObj.HeTongBianHao); wu.insertValue("基本信息_合同名称", pt.projectObj.HeTongMingCheng); wu.insertValue("基本信息_起止时间", pt.projectObj.HeTongKaiShiShiJian.ToString("yyyy年MM月dd日") + " 至" + pt.projectObj.HeTongJieShuShiJian.ToString("yyyy年MM月dd日")); wu.insertValue("基本信息_合同价款", pt.projectObj.HeTongJiaKuan.ToString()); wu.insertValue("基本信息_经费管理模式", pt.projectObj.HeTongJingFeiGuanLiMoShi); wu.insertValue("基本信息_委托_单位名称", pt.projectObj.WeiTuoDanWeiMingCheng); wu.insertValue("基本信息_承研_单位名称", pt.projectObj.ChengYanDanWeiMingCheng); wu.insertValue("基本信息_委托_单位性质", pt.projectObj.WeiTuoDanWeiXingZhi); wu.insertValue("基本信息_承研_单位性质", pt.projectObj.ChengYanDanWeiXingZhi); wu.insertValue("基本信息_委托_法定代表人", pt.projectObj.WeiTuoDanWeiFaDingDaiBiaoRen); wu.insertValue("基本信息_承研_法定代表人", pt.projectObj.ChengYanDanWeiFaDingDaiBiaoRen); wu.insertValue("基本信息_委托_联系人", pt.projectObj.WeiTuoDanWeiLianXiRen); wu.insertValue("基本信息_承研_联系人", pt.projectObj.ChengYanDanWeiLianXiRen); wu.insertValue("基本信息_委托_联系电话", pt.projectObj.WeiTuoDanWeiLianXiRenDianHua); wu.insertValue("基本信息_承研_联系电话", pt.projectObj.ChengYanDanWeiLianXiRenDianHua); wu.insertValue("基本信息_委托_通信地址", pt.projectObj.WeiTuoDanWeiTongXinDiZhi); wu.insertValue("基本信息_承研_通信地址", pt.projectObj.ChengYanDanWeiTongXinDiZhi); wu.insertValue("基本信息_委托_邮政编码", pt.projectObj.WeiTuoDanWeiYouZhengBianMa); wu.insertValue("基本信息_承研_邮政编码", pt.projectObj.ChengYanDanWeiYouZhengBianMa); wu.insertValue("基本信息_委托_组织机构代码", pt.projectObj.WeiTuoDanWeiZuZhiJiGouDaiMa); wu.insertValue("基本信息_承研_组织机构代码", pt.projectObj.ChengYanDanWeiZuZhiJiGouDaiMa); wu.insertValue("基本信息_委托_税号", pt.projectObj.WeiTuoDanWeiShuiHao); wu.insertValue("基本信息_承研_税号", pt.projectObj.ChengYanDanWeiShuiHao); wu.insertValue("基本信息_委托_开户名称", pt.projectObj.WeiTuoDanWeiKaiHuMingCheng); wu.insertValue("基本信息_承研_开户名称", pt.projectObj.ChengYanDanWeiKaiHuMingCheng); wu.insertValue("基本信息_委托_开户银行", pt.projectObj.WeiTuoDanWeiKaiHuYingHang); wu.insertValue("基本信息_承研_开户银行", pt.projectObj.ChengYanDanWeiKaiHuYingHang); wu.insertValue("基本信息_委托_银行帐号", pt.projectObj.WeiTuoDanWeiYinHangZhangHao); wu.insertValue("基本信息_承研_银行帐号", pt.projectObj.ChengYanDanWeiYinHangZhangHao); wu.insertValue("基本信息_委托_财务负责人", pt.projectObj.WeiTuoDanWeiCaiWuFuZeRen); wu.insertValue("基本信息_承研_财务负责人", pt.projectObj.ChengYanDanWeiCaiWuFuZeRen); wu.insertValue("基本信息_委托_财务联系电话", pt.projectObj.WeiTuoDanWeiCaiWuFuZeRenDianHua); wu.insertValue("基本信息_承研_财务联系电话", pt.projectObj.ChengYanDanWeiCaiWuFuZeRenDianHua); wu.insertValue("共同条款_合同数字1", ConnectionManager.Context.table("ZiDianBiao").where ("MingCheng='" + TogetherRuleEditor.TRCode1Key + "'").select("ShuJu").getValue <string>("0")); wu.insertValue("共同条款_合同数字2", ConnectionManager.Context.table("ZiDianBiao").where ("MingCheng='" + TogetherRuleEditor.TRCode2Key + "'").select("ShuJu").getValue <string>("0")); wu.insertValue("共同条款_合同数字3", ConnectionManager.Context.table("ZiDianBiao").where ("MingCheng='" + TogetherRuleEditor.TRCode3Key + "'").select("ShuJu").getValue <string>("0")); wu.insertValue("共同条款_合同数字4", ConnectionManager.Context.table("ZiDianBiao").where ("MingCheng='" + TogetherRuleEditor.TRCode4Key + "'").select("ShuJu").getValue <string>("0")); #endregion Report(progressDialog, 40, "写入文档文件...", 1000); #region 插入文档文件 wu.insertTxtFile("研究目标", Path.Combine(pt.filesDir, "研究目标.txt")); wu.insertFile("主要研究内容_项目分解情况", Path.Combine(pt.filesDir, "项目分解情况.doc"), true); wu.insertTxtFile("技术要求及指标_总技术要求", Path.Combine(pt.filesDir, "技术要求.txt")); wu.insertTxtFile("经费预算_双方认为需要说明的经费使用事项", Path.Combine(pt.filesDir, "双方认为需要说明的经费使用事项.txt")); #endregion Report(progressDialog, 60, "写入表格数据...", 1000); #region 写入表格数据 //查找所有表格 NodeCollection ncc = wu.Document.WordDoc.GetChildNodes(NodeType.Table, true); #region 插入经费预算数据 List <YuSuanBiao> ysList = ConnectionManager.Context.table("YuSuanBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <YuSuanBiao>(new YuSuanBiao()); //取数放于字典中 Dictionary <string, string> tempDict = new Dictionary <string, string>(); foreach (YuSuanBiao ysb in ysList) { tempDict[ysb.MingCheng] = ysb.ShuJu; } //生成年份名称 int yearStart = pt.projectObj.HeTongKaiShiShiJian.Year; for (int kk = 0; kk < 5; kk++) { tempDict["YearName" + (kk + 1)] = (yearStart + kk).ToString(); } foreach (Node node in ncc) { Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)node; if (t.GetText().Contains("科目名称")) { //金额 t.Rows[2].Cells[1].RemoveAllChildren(); t.Rows[2].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money1"])); ((Paragraph)t.Rows[2].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[3].Cells[1].RemoveAllChildren(); t.Rows[3].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money2"])); ((Paragraph)t.Rows[3].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[4].Cells[1].RemoveAllChildren(); t.Rows[4].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money3"])); ((Paragraph)t.Rows[4].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[5].Cells[1].RemoveAllChildren(); t.Rows[5].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money3_1"])); ((Paragraph)t.Rows[5].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[6].Cells[1].RemoveAllChildren(); t.Rows[6].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money3_2"])); ((Paragraph)t.Rows[6].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[7].Cells[1].RemoveAllChildren(); t.Rows[7].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money3_3"])); ((Paragraph)t.Rows[7].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[8].Cells[1].RemoveAllChildren(); t.Rows[8].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money4"])); ((Paragraph)t.Rows[8].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[9].Cells[1].RemoveAllChildren(); t.Rows[9].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money5"])); ((Paragraph)t.Rows[9].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[10].Cells[1].RemoveAllChildren(); t.Rows[10].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money5_1"])); ((Paragraph)t.Rows[10].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[11].Cells[1].RemoveAllChildren(); t.Rows[11].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money5_2"])); ((Paragraph)t.Rows[11].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[12].Cells[1].RemoveAllChildren(); t.Rows[12].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money6"])); ((Paragraph)t.Rows[12].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[13].Cells[1].RemoveAllChildren(); t.Rows[13].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money7"])); ((Paragraph)t.Rows[13].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[14].Cells[1].RemoveAllChildren(); t.Rows[14].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money8"])); ((Paragraph)t.Rows[14].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[15].Cells[1].RemoveAllChildren(); t.Rows[15].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money9"])); ((Paragraph)t.Rows[15].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[16].Cells[1].RemoveAllChildren(); t.Rows[16].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money10"])); ((Paragraph)t.Rows[16].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[17].Cells[1].RemoveAllChildren(); t.Rows[17].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money11"])); ((Paragraph)t.Rows[17].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[18].Cells[1].RemoveAllChildren(); t.Rows[18].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money12"])); ((Paragraph)t.Rows[18].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[19].Cells[1].RemoveAllChildren(); t.Rows[19].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Money13"])); ((Paragraph)t.Rows[19].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; //备注 t.Rows[2].Cells[2].RemoveAllChildren(); t.Rows[2].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info1"])); t.Rows[2].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[3].Cells[2].RemoveAllChildren(); t.Rows[3].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info2"])); t.Rows[3].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[4].Cells[2].RemoveAllChildren(); t.Rows[4].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info3"])); t.Rows[4].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[5].Cells[2].RemoveAllChildren(); t.Rows[5].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info3_1"])); t.Rows[5].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[6].Cells[2].RemoveAllChildren(); t.Rows[6].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info3_2"])); t.Rows[6].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[7].Cells[2].RemoveAllChildren(); t.Rows[7].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info3_3"])); t.Rows[7].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[8].Cells[2].RemoveAllChildren(); t.Rows[8].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info4"])); t.Rows[8].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[9].Cells[2].RemoveAllChildren(); t.Rows[9].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info5"])); t.Rows[9].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[10].Cells[2].RemoveAllChildren(); t.Rows[10].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info5_1"])); t.Rows[10].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[11].Cells[2].RemoveAllChildren(); t.Rows[11].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info5_2"])); t.Rows[11].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[12].Cells[2].RemoveAllChildren(); t.Rows[12].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info6"])); t.Rows[12].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[13].Cells[2].RemoveAllChildren(); t.Rows[13].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info7"])); t.Rows[13].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[14].Cells[2].RemoveAllChildren(); t.Rows[14].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info8"])); t.Rows[14].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[15].Cells[2].RemoveAllChildren(); t.Rows[15].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info9"])); t.Rows[15].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[16].Cells[2].RemoveAllChildren(); t.Rows[16].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info10"])); t.Rows[16].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[17].Cells[2].RemoveAllChildren(); t.Rows[17].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info11"])); t.Rows[17].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[18].Cells[2].RemoveAllChildren(); t.Rows[18].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info12"])); t.Rows[18].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[19].Cells[2].RemoveAllChildren(); t.Rows[19].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Info13"])); t.Rows[19].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; //年份 t.Rows[t.Rows.Count - 2].Cells[0].RemoveAllChildren(); t.Rows[t.Rows.Count - 2].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, tempDict["YearName1"] + "年度")); ((Paragraph)t.Rows[t.Rows.Count - 2].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 2].Cells[1].RemoveAllChildren(); t.Rows[t.Rows.Count - 2].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["YearName2"] + "年度")); ((Paragraph)t.Rows[t.Rows.Count - 2].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 2].Cells[2].RemoveAllChildren(); t.Rows[t.Rows.Count - 2].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["YearName3"] + "年度")); ((Paragraph)t.Rows[t.Rows.Count - 2].Cells[2].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 2].Cells[3].RemoveAllChildren(); t.Rows[t.Rows.Count - 2].Cells[3].AppendChild(wu.Document.newParagraph(t.Document, tempDict["YearName4"] + "年度")); ((Paragraph)t.Rows[t.Rows.Count - 2].Cells[3].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 2].Cells[4].RemoveAllChildren(); t.Rows[t.Rows.Count - 2].Cells[4].AppendChild(wu.Document.newParagraph(t.Document, tempDict["YearName5"] + "年度")); ((Paragraph)t.Rows[t.Rows.Count - 2].Cells[4].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; //年度金额 t.Rows[t.Rows.Count - 1].Cells[0].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Year1"])); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 1].Cells[1].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Year2"])); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 1].Cells[2].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Year3"])); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[2].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 1].Cells[3].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[3].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Year4"])); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[3].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[t.Rows.Count - 1].Cells[4].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[4].AppendChild(wu.Document.newParagraph(t.Document, tempDict["Year5"])); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[4].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; break; } } #endregion #region 插入提交要求数据 //查询数据 List <TiJiaoYaoQiuBiao> tjyqList = ConnectionManager.Context.table("TiJiaoYaoQiuBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <TiJiaoYaoQiuBiao>(new TiJiaoYaoQiuBiao()); //填充数据 foreach (Node node in ncc) { Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)node; if (t.GetText().Contains("序号") && t.GetText().Contains("名称") && t.GetText().Contains("要求")) { //创建行 for (int k = 0; k < tjyqList.Count - 1; k++) { t.Rows.Add((Aspose.Words.Tables.Row)t.Rows[t.Rows.Count - 1].Clone(true)); } int rowStart = 1; foreach (TiJiaoYaoQiuBiao data in tjyqList) { t.Rows[rowStart].Cells[0].RemoveAllChildren(); t.Rows[rowStart].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, (rowStart).ToString())); ((Paragraph)t.Rows[rowStart].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[1].RemoveAllChildren(); t.Rows[rowStart].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, data.MingCheng)); t.Rows[rowStart].Cells[1].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[2].RemoveAllChildren(); wu.Document.addRangeToNodeCollection(t.Rows[rowStart].Cells[2].ChildNodes, wu.Document.getParagraphListWithNewLine(t.Document, data.YaoQiu)); t.Rows[rowStart].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; rowStart++; } } } #endregion #region 插入经费拨付约定数据 //查询数据 List <BoFuBiao> bfydList = ConnectionManager.Context.table("BoFuBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <BoFuBiao>(new BoFuBiao()); //填充数据 foreach (Node node in ncc) { Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)node; if (t.GetText().Contains("拨付条件") && t.GetText().Contains("预计时间") && t.GetText().Contains("经费金额")) { //创建行 for (int k = 0; k < bfydList.Count - 1; k++) { t.Rows.Add((Aspose.Words.Tables.Row)t.Rows[t.Rows.Count - 1].Clone(true)); } int rowStart = 1; foreach (BoFuBiao data in bfydList) { t.Rows[rowStart].Cells[0].RemoveAllChildren(); t.Rows[rowStart].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, (rowStart).ToString())); ((Paragraph)t.Rows[rowStart].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[1].RemoveAllChildren(); wu.Document.addRangeToNodeCollection(t.Rows[rowStart].Cells[1].ChildNodes, wu.Document.getParagraphListWithNewLine(t.Document, data.BoFuTiaoJian)); t.Rows[rowStart].Cells[1].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[2].RemoveAllChildren(); t.Rows[rowStart].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, data.YuJiShiJian.ToString("yyyy年MM月"))); t.Rows[rowStart].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[3].RemoveAllChildren(); t.Rows[rowStart].Cells[3].AppendChild(wu.Document.newParagraph(t.Document, data.JingFeiJinQian.ToString())); ((Paragraph)t.Rows[rowStart].Cells[3].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[4].RemoveAllChildren(); wu.Document.addRangeToNodeCollection(t.Rows[rowStart].Cells[4].ChildNodes, wu.Document.getParagraphListWithNewLine(t.Document, data.BeiZhu)); t.Rows[rowStart].Cells[4].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; rowStart++; } } } #endregion #region 插入研究进度安排数据 //查询数据 List <JinDuBiao> jdList = ConnectionManager.Context.table("JinDuBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <JinDuBiao>(new JinDuBiao()); //填充数据 foreach (Node node in ncc) { Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)node; if (t.GetText().Contains("节点") && t.GetText().Contains("时间") && t.GetText().Contains("进度要求")) { //创建行 for (int k = 0; k < jdList.Count - 1; k++) { t.Rows.Add((Aspose.Words.Tables.Row)t.Rows[t.Rows.Count - 1].Clone(true)); } int rowStart = 1; foreach (JinDuBiao data in jdList) { t.Rows[rowStart].Cells[0].RemoveAllChildren(); t.Rows[rowStart].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, rowStart.ToString())); ((Paragraph)t.Rows[rowStart].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[1].RemoveAllChildren(); t.Rows[rowStart].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, data.ShiJian.ToString("yyyy年MM月"))); t.Rows[rowStart].Cells[1].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[2].RemoveAllChildren(); Paragraph p = wu.Document.newParagraph(t.Document, "阶段目标与研究内容:"); ((Run)p.ChildNodes[0]).Font.Bold = true; t.Rows[rowStart].Cells[2].AppendChild(p); wu.Document.addRangeToNodeCollection(t.Rows[rowStart].Cells[2].ChildNodes, wu.Document.getParagraphListWithNewLine(t.Document, data.JieDuanMuBiao)); p = wu.Document.newParagraph(t.Document, "阶段成果、考核指标及考核方式:"); ((Run)p.ChildNodes[0]).Font.Bold = true; t.Rows[rowStart].Cells[2].AppendChild(p); wu.Document.addRangeToNodeCollection(t.Rows[rowStart].Cells[2].ChildNodes, wu.Document.getParagraphListWithNewLine(t.Document, data.JieDuanChengGuo)); t.Rows[rowStart].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; rowStart++; } } } #endregion #region 插入技术要求数据 wu.Document.WordDocBuilder.MoveToBookmark("技术要求及指标_年度技术要求"); //查询数据 List <JiShuBiao> jsList = ConnectionManager.Context.table("JiShuBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <JiShuBiao>(new JiShuBiao()); int index = 1; foreach (JiShuBiao data in jsList) { wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write((index == 1 ? "" : " ") + "(" + index + ") " + data.NianDu + "年度:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.NeiRong, index == jsList.Count ? false : true); index++; } #endregion #region 插入考核方式数据 wu.Document.WordDocBuilder.MoveToBookmark("技术要求及指标_主要指标名称及要求与考核方式"); List <ZhiBiaoBiao> zbbList = ConnectionManager.Context.table("ZhiBiaoBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <ZhiBiaoBiao>(new ZhiBiaoBiao()); index = 1; foreach (ZhiBiaoBiao data in zbbList) { wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write(index + ".指标名称:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.ZhiBiaoMingCheng); wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write("(1) 指标要求:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.ZhiBiaoYaoQiu); wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write("(2) 考核方式:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.KaoHeFangShi, index == zbbList.Count ? false : true); index++; } #endregion //课题关系表 Dictionary <string, string> subjectDict = new Dictionary <string, string>(); #region 插入课题情况数据 wu.Document.WordDocBuilder.MoveToBookmark("主要研究内容_各课题情况_摘要"); List <KeTiBiao> ktList = ConnectionManager.Context.table("KeTiBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <KeTiBiao>(new KeTiBiao()); index = 1; foreach (KeTiBiao data in ktList) { string subjectRealName = "课题" + index; subjectDict[data.BianHao] = subjectRealName; wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write(subjectRealName + ":"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.KeTiMingCheng); wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Write("(1)研究目标:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.KeTiYanJiuMuBiao); wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Writeln("(2)研究内容:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.KeTiYanJiuNeiRong); wu.Document.WordDocBuilder.Font.Bold = true; wu.Document.WordDocBuilder.Writeln("(3)参加单位分工:"); wu.Document.WordDocBuilder.Font.Bold = false; wu.Document.writeWithNewLine(data.KeTiCanJiaDanWeiFenGong, index == ktList.Count ? false : true); index++; } #endregion #region 插入人员数据 //查询数据 List <RenYuanBiao> rylist = ConnectionManager.Context.table("RenYuanBiao").orderBy("ZhuangTai,ModifyTime").select("*").getList <RenYuanBiao>(new RenYuanBiao()); //填充数据 foreach (Node node in ncc) { Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)node; if (t.GetText().Contains("任务分工") && t.GetText().Contains("身份证号码") && t.GetText().Contains("项目中职务")) { //创建行 for (int k = 0; k < rylist.Count - 1; k++) { t.Rows.Insert(1, (Aspose.Words.Tables.Row)t.Rows[t.Rows.Count - 2].Clone(true)); } int totalMonth = 0; int rowStart = 1; foreach (RenYuanBiao data in rylist) { totalMonth += data.MeiNianTouRuShiJian; t.Rows[rowStart].Cells[0].RemoveAllChildren(); t.Rows[rowStart].Cells[0].AppendChild(wu.Document.newParagraph(t.Document, (rowStart).ToString())); ((Paragraph)t.Rows[rowStart].Cells[0].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[1].RemoveAllChildren(); t.Rows[rowStart].Cells[1].AppendChild(wu.Document.newParagraph(t.Document, data.XingMing)); t.Rows[rowStart].Cells[1].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[2].RemoveAllChildren(); t.Rows[rowStart].Cells[2].AppendChild(wu.Document.newParagraph(t.Document, data.XingBie)); t.Rows[rowStart].Cells[2].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[3].RemoveAllChildren(); t.Rows[rowStart].Cells[3].AppendChild(wu.Document.newParagraph(t.Document, data.ZhiCheng)); t.Rows[rowStart].Cells[3].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[4].RemoveAllChildren(); t.Rows[rowStart].Cells[4].AppendChild(wu.Document.newParagraph(t.Document, data.ZhuanYe)); t.Rows[rowStart].Cells[4].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[5].RemoveAllChildren(); t.Rows[rowStart].Cells[5].AppendChild(wu.Document.newParagraph(t.Document, data.GongZuoDanWei)); t.Rows[rowStart].Cells[5].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[6].RemoveAllChildren(); t.Rows[rowStart].Cells[6].AppendChild(wu.Document.newParagraph(t.Document, data.MeiNianTouRuShiJian + "")); ((Paragraph)t.Rows[rowStart].Cells[6].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; t.Rows[rowStart].Cells[7].RemoveAllChildren(); t.Rows[rowStart].Cells[7].AppendChild(wu.Document.newParagraph(t.Document, data.RenWuFenGong)); t.Rows[rowStart].Cells[7].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; t.Rows[rowStart].Cells[8].RemoveAllChildren(); t.Rows[rowStart].Cells[8].AppendChild(wu.Document.newParagraph(t.Document, data.ShenFenZhengHao)); t.Rows[rowStart].Cells[8].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; string roleName = "未知"; switch (data.ShiXiangMuFuZeRen) { case "rbIsOnlyProject": roleName = "项目负责人"; break; case "rbIsProjectAndSubject": roleName = "项目负责人兼" + (subjectDict.ContainsKey(data.KeTiBiaoHao) ? subjectDict[data.KeTiBiaoHao] + data.ZhiWu : "未知"); break; case "rbIsOnlySubject": roleName = subjectDict.ContainsKey(data.KeTiBiaoHao) ? subjectDict[data.KeTiBiaoHao] + data.ZhiWu : "未知"; break; } t.Rows[rowStart].Cells[9].RemoveAllChildren(); t.Rows[rowStart].Cells[9].AppendChild(wu.Document.newParagraph(t.Document, roleName)); t.Rows[rowStart].Cells[9].CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; rowStart++; } t.Rows[t.Rows.Count - 1].Cells[t.Rows[t.Rows.Count - 1].Cells.Count - 1].RemoveAllChildren(); t.Rows[t.Rows.Count - 1].Cells[t.Rows[t.Rows.Count - 1].Cells.Count - 1].AppendChild(wu.Document.newParagraph(t.Document, ((float)totalMonth / (float)12).ToString("0.00"))); ((Paragraph)t.Rows[t.Rows.Count - 1].Cells[t.Rows[t.Rows.Count - 1].Cells.Count - 1].ChildNodes[0]).ParagraphFormat.Alignment = ParagraphAlignment.Center; } } #endregion #endregion Report(progressDialog, 80, "更新目录...", 1000); #region 更新目录 //try //{ // wu.WordDoc.Styles["目录 1"].Font.NameFarEast = "黑体"; // wu.WordDoc.Styles["目录 1"].Font.Size = 14; // wu.WordDoc.Styles["目录 1"].Font.Bold = 0; // wu.WordDoc.Styles["目录 1"].Font.Italic = 0; // wu.WordDoc.Styles["目录 2"].Font.NameFarEast = "楷体"; // wu.WordDoc.Styles["目录 2"].Font.NameAscii = wu.WordDoc.Styles["目录 1"].Font.NameAscii; // wu.WordDoc.Styles["目录 2"].Font.NameBi = wu.WordDoc.Styles["目录 1"].Font.NameBi; // wu.WordDoc.Styles["目录 2"].Font.NameOther = wu.WordDoc.Styles["目录 1"].Font.NameOther; // wu.WordDoc.Styles["目录 2"].Font.Size = 12; // wu.WordDoc.Styles["目录 2"].Font.Bold = 0; // wu.WordDoc.Styles["目录 2"].Font.Italic = 0; // wu.WordDoc.Styles["目录 3"].Font.NameFarEast = "楷体"; // wu.WordDoc.Styles["目录 3"].Font.NameAscii = wu.WordDoc.Styles["目录 1"].Font.NameAscii; // wu.WordDoc.Styles["目录 3"].Font.NameBi = wu.WordDoc.Styles["目录 1"].Font.NameBi; // wu.WordDoc.Styles["目录 3"].Font.NameOther = wu.WordDoc.Styles["目录 1"].Font.NameOther; // wu.WordDoc.Styles["目录 3"].Font.Size = 12; // wu.WordDoc.Styles["目录 3"].Font.Bold = 0; // wu.WordDoc.Styles["目录 3"].Font.Italic = 0; // object missing = System.Reflection.Missing.Value; // Microsoft.Office.Interop.Word.Range myRange = wu.WordDoc.TablesOfContents[1].Range; // wu.WordDoc.TablesOfContents[1].Delete(); // object useHeadingStyle = true; //使用Head样式 // object upperHeadingLevel = 1; //最大一级 // object lowerHeadingLevel = 2; //最小三级 // object useHypeLinks = true; // //TablesOfContents的Add方法添加目录 // wu.WordDoc.TablesOfContents.Add(myRange, ref useHeadingStyle, // ref upperHeadingLevel, ref lowerHeadingLevel, // ref missing, ref missing, ref missing, ref missing, // ref missing, ref useHypeLinks, ref missing, ref missing); // wu.WordDoc.TablesOfContents[1].TabLeader = Microsoft.Office.Interop.Word.WdTabLeader.wdTabLeaderDots; //} //catch (Exception ex) { } //wu.WordDoc.ResetFormFields(); //wu.WordDoc.Fields.Update(); wu.Document.WordDoc.UpdateFields(); wu.Document.WordDoc.UpdateListLabels(); wu.Document.WordDoc.UpdatePageLayout(); wu.Document.WordDoc.UpdateTableLayout(); wu.Document.WordDoc.UpdateThumbnail(); wu.Document.WordDoc.UpdateWordCount(); #endregion Report(progressDialog, 90, "生成文档...", 1000); #region 显示文档或生成文档 //关闭word wu.killWinWordProcess(); //保存word string docFile = Path.Combine(pt.dataDir, "合同书.doc"); wu.saveDocument(docFile); Process.Start(docFile); #endregion } catch (Exception ex) { MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } Report(progressDialog, 95, "", 1000); }
public override void Evaluate(NBMessageAssembly inputAssembly) { NBOutputTerminal outTerminal = OutputTerminal("Out"); NBMessage inputMessage = inputAssembly.Message; // Create a new message from a copy of the inboundMessage, ensuring it is disposed of after use using (NBMessage outputMessage = new NBMessage(inputMessage)) { isError = false; NBMessageAssembly outAssembly = new NBMessageAssembly(inputAssembly, outputMessage); NBElement inputRoot = inputMessage.RootElement; NBElement outputRoot = outputMessage.RootElement; #region UserCode try { // check if we need to just do a test if (inputRoot["JSON"]["Data"]["headTest"] == null) { requestId = inputRoot["JSON"]["Data"]["requestId"].ValueAsString; if (inputRoot["JSON"]["Data"]["asyncRequest"] != null) { String uploadFileName = ""; if (inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["isZipUpload"].ValueAsString == "FALSE") { uploadFileName = inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["generatedName"].ValueAsString; uploadFileName = ReplaceDateTimeReferences(uploadFileName); } getUploadFileLocation(outputRoot, uploadFileName, inputRoot, requestId); } else { outputRoot["JSON"]["Data"].DeleteAllChildren(); applyLicense(outputRoot); if (isError == false) { var pdfStreams = new List <PDFStream>(); var nonZipPDFStreams = new List <PDFStream>(); foreach (NBElement template in inputRoot["JSON"]["Data"]["templateDetails"]["templates"]) { String patentDataItem = template["parentDataItem"].ValueAsString; String csvCollatedFile = ""; String isZipUpload = template["isZipUpload"].ValueAsString; String inputFileExtension = Path.GetExtension(template["templateName"].ValueAsString.ToUpper()); String outputFileExtension = Path.GetExtension(template["generatedName"].ValueAsString.ToUpper()); InputFileTypes inputFileType = (InputFileTypes)Enum.Parse(typeof(InputFileTypes), inputFileExtension.Replace(".", ""), true); OutputFileTypes outputFileType = (OutputFileTypes)Enum.Parse(typeof(OutputFileTypes), outputFileExtension.Replace(".", ""), true); String templateContent = ""; if (inputFileType != InputFileTypes.CSV) { templateContent = System.IO.File.ReadAllText(template["templateLocation"].ValueAsString); } NBElement envIn = inputRoot["JSON"]["Data"]; String documentIdentifierField = ""; if (envIn["documentIdentifierField"] != null) { documentIdentifierField = envIn["documentIdentifierField"].ValueAsString; } Boolean elementFound = true; foreach (String elementName in patentDataItem.Split('.')) { if (envIn[elementName] != null) { envIn = envIn[elementName]; } else { elementFound = false; break; } } if (elementFound == true && envIn.Children().Count() > 0) { List <NBElement> elementsToProcess = new List <NBElement>(); if (envIn.FirstChild.Name == "Item" && envIn.LastChild.Name == "Item") { elementsToProcess = envIn.ToList(); } else { elementsToProcess.Add(envIn); } String outputFileName = template["generatedName"].ValueAsString; if (outputFileType != OutputFileTypes.CSV) { Parallel.ForEach(elementsToProcess, docData => { String documentContent = templateContent; String templateName = outputFileName; String identifier = ""; if (documentIdentifierField != "") { identifier = ReplaceAllFields(docData, "[[" + documentIdentifierField + "]]"); isZipUpload = "FALSE"; } documentContent = ReplaceAllFields(docData, documentContent); templateName = ReplaceAllFields(docData, templateName); //Example of IF field - [[IFdepositAccount!=""|Deposit Account|]] Regex ifregex = new Regex(string.Format("\\[IF.*?\\]]")); foreach (Match m in ifregex.Matches(documentContent)) { String fieldContent = getFieldContent(docData, m.Value.Replace("[", "").Replace("]", "")); documentContent = documentContent.Replace("[" + m.Value, fieldContent); } //Example of IF field - [[FORMATrenewalDate|dd-MM-yyyy]] Regex formatregex = new Regex(string.Format("\\[FORMAT.*?\\]]")); foreach (Match m in formatregex.Matches(documentContent)) { String fieldName = m.Value.Replace("[", "").Replace("]", ""); if (fieldName.IndexOf('|') > -1) { String fieldFormat = fieldName.Split('|')[1]; fieldName = fieldName.Split('|')[0].Replace("FORMAT", ""); String fieldContent = ReplaceAllFields(docData, "[[" + fieldName + "]]"); if (fieldContent != "") { switch (fieldFormat.ToLower()) { case "caps": fieldContent = fieldContent.First().ToString().ToUpper() + fieldContent.Substring(1); break; case "camelcase": fieldContent = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fieldContent); break; case "lower": fieldContent = fieldContent.ToLower(); break; case "upper": fieldContent = fieldContent.ToUpper(); break; default: try { DateTime parsedDate; String pattern = "yyyy-MM-dd"; if (DateTime.TryParseExact(fieldContent, pattern, null, System.Globalization.DateTimeStyles.None, out parsedDate)) { fieldContent = String.Format("{0:" + fieldFormat + "}", parsedDate); } else { fieldContent = String.Format("{0:" + fieldFormat + "}", fieldContent); } } catch { } break; } } documentContent = documentContent.Replace("[" + m.Value, fieldContent); } } List <string> tables = new List <string>(); String docTable = documentContent; while (docTable.IndexOf("[[##TABLE") > 0) { int start = docTable.IndexOf("[[##TABLE"); int end = docTable.IndexOf("TABLE##]]"); if (end <= 0) { break; } tables.Add(docTable.Substring(start + 9, end - start - 10)); docTable = docTable.Substring(end + 1); } var rtfBuilder = new RTFBuilder(); List <String> tableNames = new List <string>(); // replace any table definitions foreach (String table in tables) { // Get Column Definitions String groupDataItem = ""; String tableName = ""; List <CommonDefinitions.ColumnDefinition> colDefs = new List <CommonDefinitions.ColumnDefinition>(); List <CommonDefinitions.TotalColumns> totalCols = new List <CommonDefinitions.TotalColumns>(); foreach (String sColDef in table.Split('|')) { if (sColDef == table.Split('|')[0]) { tableName = sColDef.Split(':')[0]; groupDataItem = sColDef.Split(':')[1]; } else { if (sColDef.Split(':').Count() == 2) { colDefs.Add(new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1])); } if (sColDef.Split(':').Count() == 3) { CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2]); colDefs.Add(colDef); if (colDef.isTotalColumn == true) { totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName)); } } if (sColDef.Split(':').Count() == 4) { CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2], sColDef.Split(':')[3]); colDefs.Add(colDef); if (colDef.isTotalColumn == true) { totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName)); } } } } tableNames.Add(tableName); byte[] tableByteArray = Encoding.ASCII.GetBytes(documentContent); MemoryStream tableStream = new MemoryStream(tableByteArray); //Document tableDoc = new Document(tableStream); Document tableDoc = new Document(); DocumentBuilder builder = new DocumentBuilder(tableDoc); builder.Write("##" + tableName + "START##"); builder.Writeln(); Aspose.Words.Tables.Table tbl = builder.StartTable(); builder.CellFormat.Borders.Top.LineStyle = LineStyle.None; builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Right.LineStyle = LineStyle.None; builder.CellFormat.Borders.Left.LineStyle = LineStyle.None; builder.CellFormat.TopPadding = 4; builder.CellFormat.BottomPadding = 4; builder.CellFormat.LeftPadding = 0; ParagraphFormat paragraphFormat = builder.ParagraphFormat; paragraphFormat.Alignment = ParagraphAlignment.Left; paragraphFormat.LeftIndent = 0; builder.Font.Name = "Arial"; builder.Font.Size = 10; builder.Font.Bold = true; builder.Font.Bold = false; Color headerFont = new Color(); headerFont = Color.FromArgb(39, 55, 96); builder.Font.Color = headerFont; foreach (CommonDefinitions.ColumnDefinition colDef in colDefs) { builder.InsertCell(); if (colDef == colDefs.First()) { builder.StartBookmark(tableName + "START"); builder.EndBookmark(tableName + "START"); } tbl.LeftIndent = -42; tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write(colDef.columnName); } builder.EndRow(); NBElement rowItems = docData; foreach (String elementName in groupDataItem.Split('.')) { rowItems = rowItems[elementName]; } builder.Font.Bold = false; Color contentFont = new Color(); contentFont = Color.FromArgb(128, 128, 128); builder.Font.Color = contentFont; int rowId = 1; //foreach (NBElement row in rowItems) //{ foreach (ColumnDefinition colDef in colDefs) { builder.InsertCell(); tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write("[[" + colDef.fieldName + "]]"); } rowId++; builder.EndRow(); foreach (ColumnDefinition colDef in colDefs) { builder.InsertCell(); tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write("[[" + colDef.fieldName + "Last]]"); } rowId++; builder.EndRow(); builder.EndTable(); builder.Writeln(); builder.Write("##" + tableName + "END##"); MemoryStream rtfTableStream = new MemoryStream(); tableDoc.Save(rtfTableStream, SaveFormat.Rtf); Byte[] rtfByteArray = rtfTableStream.ToArray(); String rtfDocString = Encoding.ASCII.GetString(rtfByteArray); String tableRowString = rtfDocString.Substring(rtfDocString.IndexOf("}\\trowd\\irow1\\") + 1, rtfDocString.IndexOf("}\\trowd\\irow2\\") - rtfDocString.IndexOf("}\\trowd\\irow1\\")); int insertIndex = rtfDocString.IndexOf(tableRowString) + tableRowString.Length; //String tableContents = ""; StringBuilder tableContents = new StringBuilder(rtfDocString.Substring(0, insertIndex)); int rowCount = 2; foreach (NBElement row in rowItems) { String rowString = tableRowString; foreach (ColumnDefinition colDef in colDefs) { String sData = ""; if (colDef.fieldName != "lineNo") { if (row[colDef.fieldName] != null) { sData = row[colDef.fieldName].ValueAsString; if (sData.ToUpper() == "NULL") { sData = ""; } } else { sData = colDef.defaultValue; } } else { sData = (rowCount - 1).ToString(); } if (rowCount < rowItems.Count() + 1) { rowString = rowString.Replace("[[" + colDef.fieldName + "]]", sData); } else { rtfDocString = rtfDocString.Replace("[[" + colDef.fieldName + "Last]]", sData); } } if (rowCount < rowItems.Count() + 1) { rowString = rowString.Replace("irow1", "irow" + rowCount.ToString()); tableContents.Append(rowString); } rowCount++; } tableContents.Replace(tableRowString, ""); tableContents.Append(rtfDocString.Substring(insertIndex)); String tableOnly = tableContents.ToString(); //tableOnly = tableOnly.Substring(tableOnly.IndexOf(@"\trowd", tableOnly.Length - tableOnly.IndexOf(@"{\*\latentstyles"))); int startIndex = tableOnly.IndexOf("##" + tableName + "START##") + ("##" + tableName + "START##").Length; int endIndex = tableOnly.IndexOf("##" + tableName + "END##"); tableOnly = tableOnly.Substring(startIndex, endIndex - startIndex); documentContent = documentContent.Replace("[[##TABLE" + table + "|TABLE##]]", tableOnly); } // replace any items not found in the dataset Regex regex = new Regex(string.Format("\\[.*?\\]]")); documentContent = regex.Replace(documentContent, ""); templateName = ReplaceDateTimeReferences(templateName); byte[] byteArray = Encoding.ASCII.GetBytes(documentContent); MemoryStream stream = new MemoryStream(byteArray); Document doc = new Document(stream); stream.Dispose(); //String tempFileName = @"c:\temp\FileTest\" + Guid.NewGuid().ToString(); //File.WriteAllText(tempFileName, documentContent); //Document doc = new Document(tempFileName); //File.Delete(tempFileName); foreach (String tableName in tableNames) { Bookmark bm = doc.Range.Bookmarks[tableName + "START"]; Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)bm.BookmarkStart.GetAncestor(NodeType.Table); foreach (Aspose.Words.Tables.Cell c in t.GetChildNodes(NodeType.Cell, true)) { foreach (Run run in c.GetChildNodes(NodeType.Run, true)) { Aspose.Words.Font font = run.Font; Color contentFont = new Color(); contentFont = Color.FromArgb(128, 128, 128); font.Color = contentFont; font.Name = "Arial"; } } foreach (Aspose.Words.Tables.Cell c in t.FirstRow.Cells) { foreach (Run run in c.GetChildNodes(NodeType.Run, true)) { Aspose.Words.Font font = run.Font; Color contentFont = new Color(); contentFont = Color.FromArgb(39, 55, 96); font.Color = contentFont; font.Name = "Arial"; font.Bold = true; } } } MemoryStream pdfStream = new MemoryStream(); doc.Save(pdfStream, SaveFormat.Pdf); PDFStream pdfs = new PDFStream(pdfStream.ToArray(), templateName, identifier); pdfStream.Close(); if (isZipUpload == "TRUE") { pdfStreams.Add(pdfs); } else { nonZipPDFStreams.Add(pdfs); } //} }); } if (outputFileType == OutputFileTypes.CSV) { foreach (NBElement docData in elementsToProcess) { csvCollatedFile = docData["headerRow"].ValueAsString; csvCollatedFile += Environment.NewLine; Boolean isFirstRow = true; foreach (NBElement row in docData["rows"]) { if (isFirstRow == true) { isFirstRow = false; } else { csvCollatedFile += Environment.NewLine; } csvCollatedFile += row.ValueAsString; } } byte[] byteArray = Encoding.ASCII.GetBytes(csvCollatedFile); outputFileName = ReplaceDateTimeReferences(outputFileName); outputFileName = getUploadFileName(outputFileName, inputRoot); if (isZipUpload == "TRUE") { pdfStreams.Add(new PDFStream(byteArray, outputFileName)); } else { nonZipPDFStreams.Add(new PDFStream(byteArray, outputFileName)); } } } } if (pdfStreams.Count() > 0) { byte[] zipContent = writeContentToZip(pdfStreams, outputRoot); writeFileToBlobStore(outputRoot, zipContent, inputRoot, requestId); } if (nonZipPDFStreams.Count() > 0) { writeMultiFilesToBlobStore(outputRoot, nonZipPDFStreams, inputRoot, requestId); outputRoot["JSON"]["Data"].CreateFirstChild("requestId").SetValue(requestId); } } } } else { outputRoot["JSON"]["Data"].DeleteAllChildren(); checkBlobStore(inputRoot, outputRoot); } } catch (Exception e) { handleError("PDF10000", e, outputRoot, "General Error in PDF Generation Process"); } #endregion UserCode // Change the following if not propagating message to the 'Out' terminal outTerminal.Propagate(outAssembly); } }
/// <summary> /// 转换到PDF文件 /// </summary> /// <param name="destDocFile"></param> private void convertToPDF(string projectNumber, string destDocFile) { try { //Document文档对象 Aspose.Words.Document xDoc = new Aspose.Words.Document(destDocFile); //获得附件表格 Aspose.Words.Tables.Table tablee = (Aspose.Words.Tables.Table)xDoc.GetChild(Aspose.Words.NodeType.Table, xDoc.GetChildNodes(Aspose.Words.NodeType.Table, true).Count - 1, true); //行与 int rowIndex = 0; //查找需要替换位置 if (tablee != null && tablee.Rows != null) { //表格有效 foreach (Aspose.Words.Tables.Row row in tablee.Rows) { if (row.Cells[0].GetText().Contains("序号")) { continue; } else { //行号+1 rowIndex++; //清理单位格内容 row.Cells[0].Paragraphs.Clear(); //写行号 Aspose.Words.Paragraph p = new Aspose.Words.Paragraph(xDoc); p.AppendChild(new Aspose.Words.Run(xDoc, rowIndex.ToString())); row.Cells[0].AppendChild(p); } } } else { //表格无效 MainForm.writeLog("没有找到附件清单,当前文件" + destDocFile + ",表格数量:" + xDoc.GetChildNodes(Aspose.Words.NodeType.Table, true).Count); } //保存为PDF xDoc.Save(Path.Combine(new FileInfo(destDocFile).DirectoryName, "项目申报书.pdf"), Aspose.Words.SaveFormat.Pdf); } catch (Exception ex) { MainForm.writeLog(ex.ToString()); //尝试取文件名称 string fileName = destDocFile; try { fileName = new FileInfo(destDocFile).Name; } catch (Exception exxx) { } //检查是不是出现了保存成PDF时内存溢出 addErrorFile(projectNumber, fileName, "PDF转换失败"); } //删除Doc文档 try { File.Delete(destDocFile); } catch (Exception ex) { MainForm.writeLog(ex.ToString()); } }
public object SetWordFile(string TemplateNameID, string ContractNumber, string fileName) { string GUID = System.Guid.NewGuid().ToString(); var flag = true; try { //获取sql语句、模版名称 string SQL = "SELECT TemplateName,sqlstr,DataBaseUrl FROM I_TemplateFile WHERE ObjectID ='" + TemplateNameID + "'"; DataTable dt = OThinker.H3.Controllers.AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(SQL); //模版名称 var TemplateName = dt.Rows[0]["TemplateName"]; var datasource = dt.Rows[0]["DataBaseUrl"].ToString(); if (string.IsNullOrEmpty(datasource)) { datasource = "cap"; } string SQL1 = "SELECT sqlstring FROM I_TemplateFile_SQL WHERE ParentObjectID ='" + TemplateNameID + "'"; DataTable dtstr = OThinker.H3.Controllers.AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(SQL1); //模版地址 string path = System.AppDomain.CurrentDomain.BaseDirectory; path += "Sheets\\Model\\" + TemplateName + ".doc"; var document = new Document(path); var builder = new DocumentBuilder(document); //查模版维护表获取标签值 for (int i = 0; i < dtstr.Rows.Count; i++) { string sqlstr = dtstr.Rows[i]["sqlstring"].ToString(); sqlstr = HttpUtility.HtmlDecode(sqlstr); // wangxg 19.12 HTML解码 string sql1 = string.Format(sqlstr, ContractNumber.Trim()); // "Br-A000056000"); DataTable dt1 = ExecuteDataTableSql(datasource, sql1); if (dt1.Rows.Count > 0) { //确定为还款计划表 if (dt1.Columns[0].ColumnName == "CUSTOMER_RENTAL_ID") { NodeCollection allTables = document.GetChildNodes(NodeType.Table, true); //拿到所有表格 Aspose.Words.Tables.Table table = allTables[2] as Aspose.Words.Tables.Table; //拿到第二个表格 for (int l = 0; l < dt1.Rows.Count; l++) { // 复制上一行 Aspose.Words.Tables.Row clonedRow = (Aspose.Words.Tables.Row)table.LastRow.Clone(true); for (int j = 0; j < clonedRow.Count; j++) { clonedRow.Cells[j].RemoveAllChildren(); //清除单元格中内容 Aspose.Words.Paragraph p = new Aspose.Words.Paragraph(document); var CellVal = dt1.Rows[l][j] + string.Empty; CellVal = CellVal.Replace("/", "-").Replace("0:00:00", ""); p.AppendChild(new Aspose.Words.Run(document, CellVal)); clonedRow.Cells[j].AppendChild(p); } table.Rows.Add(clonedRow); //添加一行 } } else { //取标签 给标签赋值 foreach (DataColumn dc in dt1.Columns) { if (document.Range.Bookmarks[dc.ColumnName] != null) { document.Range.Bookmarks[dc.ColumnName].Text = dt1.Rows[0][dc.ColumnName].ToString(); } } } } } //文件名称//存在则覆盖,采用原来fileName if (string.IsNullOrEmpty(fileName)) { fileName = ContractNumber + TemplateName + GUID; } //测试 判断是否重新生成 //else //{ // string filePath = Server.MapPath("~/TemplateFile/") + fileName + ".pdf"; // document.Save(filePath, SaveFormat.Pdf); //} //string filePathDocold = Server.MapPath("~/TemplateFile/Doc/") + fileName + ".DOC"; //string filePathDoc = System.AppDomain.CurrentDomain.BaseDirectory + "\\PrintFilePath\\" + fileName + ".doc"; string filePathDoc = GetfilePath() + fileName + ".DOC"; OThinker.H3.Controllers.AppUtility.Engine.LogWriter.Write("filePathDoc=" + filePathDoc); //PdfSaveOptions saveOption = new PdfSaveOptions(); //saveOption.SaveFormat = Aspose.Words.SaveFormat.Pdf; ////user pass 设置了打开时,需要密码 ////owner pass 控件编辑等权限 //PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(string.Empty, "PasswordHere", PdfEncryptionAlgorithm.RC4_128); //encryptionDetails.Permissions = PdfPermissions.DisallowAll; //saveOption.EncryptionDetails = encryptionDetails; //加密文档保存到指定地点---//使用ntko不需要使用pdf暂时注释 // document.Save(filePath, saveOption); //如不不需要保存doc 请注释下句 document.Save(filePathDoc, SaveFormat.Doc); } catch (Exception e) { OThinker.H3.Controllers.AppUtility.Engine.LogWriter.Write(e.ToString()); flag = false; } return(new { Flag = flag, FileName = fileName }); }
public override VisitorAction VisitTableStart(Aspose.Words.Tables.Table table) { this.structureBuilder.AppendLine("<Table>"); return(VisitorAction.Continue); }
public object SetWordFile(string TemplateNameID, string ContractNumber) { string GUID = Guid.NewGuid().ToString(); var flag = true; var message = ""; var TemplateName = ""; var instanceType = ""; var SavedDataField = ""; string fileName = ""; double rate_fixed = 0; double rate_base = 0; double rate_float = 0; bool isNewContract = false; try { //获取sql语句、模版名称 string SQL = "SELECT TemplateName,sqlstr,DataBaseUrl,instancetype,SavedDataField FROM I_TemplateFile WHERE ObjectID ='" + TemplateNameID + "'"; DataTable dt = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(SQL); //模版名称 TemplateName = dt.Rows[0]["TemplateName"] + string.Empty; instanceType = dt.Rows[0]["instancetype"] + string.Empty; SavedDataField = dt.Rows[0]["SavedDataField"] + string.Empty; string loanContractField = ConfigurationManager.AppSettings["LoanContractSavedDataField"] + string.Empty; if (string.IsNullOrEmpty(SavedDataField)) { return(new { Flag = false, FileName = "", Id = "", Message = "未设置保存的数据项编码,请联系管理员" }); } #region 处理打印合同 // 打印合同 if (loanContractField.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(SavedDataField)) { string sql = $"SELECT ACTUAL_RTE FROM APPLICATION_CONTRACT_VW WHERE APPLICATION_NUMBER = '{ContractNumber}'"; decimal actualRte = Convert.ToDecimal((ExecuteDataTableSql("cap", sql).Rows[0]["ACTUAL_RTE"] + string.Empty)); sql = $"SELECT STATUS_CODE FROM APPLICATION@TO_CMS WHERE APPLICATION_NUMBER = '{ContractNumber}'"; string statusCode = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteScalar(sql) + string.Empty; if (statusCode == "55") { // 已放款状态,取上一次的打印记录 sql = $@"SELECT * FROM ( SELECT TEMPLATENAME, RATE_FIXED, RATE_BASE, RATE_FLOAT FROM C_CONTRACTDETAIL WHERE APPLICATIONNUMBER = '{ContractNumber}' ORDER BY CREATEDTIME DESC) WHERE ROWNUM = 1"; DataTable recordTable = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql); if (recordTable.Rows.Count == 0) { // 没有打印记录,返回false return(new { Flag = false, Message = "没有找到打印记录" }); } else { TemplateName = recordTable.Rows[0]["TEMPLATENAME"] + string.Empty; string oldUserTemplateName = ConfigurationManager.AppSettings["OldUserLoanContractName"] + string.Empty; string oldOrgTemplateName = ConfigurationManager.AppSettings["OldOrgLoanContractName"] + string.Empty; // 有打印记录 // 个人模板并且模板名称不等于维护的老个人模板名称 // 机构模板并且模板名称不等于维护的老机构模板名称 if ((instanceType == "个人" && TemplateName != oldUserTemplateName) || (instanceType == "机构" && TemplateName != oldOrgTemplateName)) { isNewContract = true; rate_fixed = Convert.ToDouble(recordTable.Rows[0]["RATE_FIXED"]); rate_base = Convert.ToDouble(recordTable.Rows[0]["RATE_BASE"]); rate_float = Convert.ToDouble(recordTable.Rows[0]["RATE_FLOAT"]); } } } else { //未放款状态,打印新合同 string rateSql = $@" SELECT {actualRte} RATE_FIXED, RATEBASE RATE_BASE, {actualRte} - RATEBASE AS RATE_FLOAT FROM ( SELECT HTLL.RATEBASE FROM I_HTLL2 HTLL INNER JOIN ( SELECT CASE WHEN LEASE_TERMS/12 > 1 THEN '5年' ELSE '1年' END LEASE_TERMS, createdtime FROM (select a.createdtime, b.lease_term_in_month as lease_terms from i_application a inner join i_Contract_Detail b on b.parentobjectid = a.objectid where a.application_number = '{ContractNumber}' ) ) CONTRACT ON HTLL.DURATION = CONTRACT.LEASE_TERMS and to_date('{DateTime.Now.ToShortDateString()}', 'yyyy/MM/dd') >= htll.enabledtime WHERE HTLL.ISDELETE = 0 ORDER BY HTLL.ENABLEDTIME DESC ) "; DataTable rateTable = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(rateSql); // 没有维护LPR,就不让打印 if (rateTable.Rows.Count == 0) { return(new { Flag = false, Message = "没有找到对应LPR记录,请维护" }); } else { isNewContract = true; rate_fixed = Convert.ToDouble(rateTable.Rows[0]["RATE_FIXED"]); rate_base = Convert.ToDouble(rateTable.Rows[0]["RATE_BASE"]); rate_float = Convert.ToDouble(rateTable.Rows[0]["RATE_FLOAT"]); } } } #endregion var datasource = dt.Rows[0]["DataBaseUrl"] + string.Empty; if (string.IsNullOrEmpty(datasource)) { datasource = "cap"; } string SQL1 = "SELECT sqlstring FROM I_TemplateFile_SQL WHERE ParentObjectID ='" + TemplateNameID + "'"; DataTable dtstr = AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(SQL1); //模版地址 string path = AppDomain.CurrentDomain.BaseDirectory; path += "Sheets\\Model\\" + TemplateName + ".doc"; var document = new Document(path); var builder = new DocumentBuilder(document); //查模版维护表获取标签值 for (int i = 0; i < dtstr.Rows.Count; i++) { string sqlstr = dtstr.Rows[i]["sqlstring"].ToString(); sqlstr = HttpUtility.HtmlDecode(sqlstr); // wangxg 19.12 HTML解码 string sql1 = string.Format(sqlstr, ContractNumber.Trim()); // "Br-A000056000"); DataTable dataSource = ExecuteDataTableSql(datasource, sql1); //记录打印查询出的数据源; AppUtility.Engine.LogWriter.Write(ContractNumber + TemplateName + GUID + "数据源" + (i + 1) + "\r\n" + Newtonsoft.Json.JsonConvert.SerializeObject(dataSource)); if (dataSource.Rows.Count > 0) { //确定为还款计划表 if (dataSource.Columns[0].ColumnName == "CUSTOMER_RENTAL_ID") { NodeCollection allTables = document.GetChildNodes(NodeType.Table, true); //拿到所有表格 Aspose.Words.Tables.Table table = allTables[2] as Aspose.Words.Tables.Table; //拿到第二个表格 for (int l = 0; l < dataSource.Rows.Count; l++) { // 复制上一行 Aspose.Words.Tables.Row clonedRow = (Aspose.Words.Tables.Row)table.LastRow.Clone(true); for (int j = 0; j < clonedRow.Count; j++) { clonedRow.Cells[j].RemoveAllChildren(); //清除单元格中内容 Aspose.Words.Paragraph p = new Aspose.Words.Paragraph(document); var CellVal = dataSource.Rows[l][j] + string.Empty; CellVal = CellVal.Replace("/", "-").Replace("0:00:00", ""); p.AppendChild(new Aspose.Words.Run(document, CellVal)); clonedRow.Cells[j].AppendChild(p); } table.Rows.Add(clonedRow); //添加一行 } } else { //取标签 给标签赋值 foreach (DataColumn dc in dataSource.Columns) { if (document.Range.Bookmarks[dc.ColumnName] != null) { if (instanceType.ToString() == "正源" && dc.DataType.ToString() == "System.DateTime") { document.Range.Bookmarks[dc.ColumnName].Text = Convert.ToDateTime(dataSource.Rows[0][dc.ColumnName].ToString()).ToString("yyyy-MM-dd"); } else { document.Range.Bookmarks[dc.ColumnName].Text = dataSource.Rows[0][dc.ColumnName].ToString(); } } } } } } // 如果是新合同,给rate_fixed, rate_base, rate_float三个书签赋值 if (isNewContract) { document.Range.Bookmarks["rate_fixed"].Text = rate_fixed.ToString(); document.Range.Bookmarks["rate_base"].Text = rate_base.ToString(); document.Range.Bookmarks["rate_float"].Text = rate_float.ToString(); } fileName = ContractNumber + TemplateName + GUID; #region Save string tempfilePath = Server.MapPath("~/TempImages/") + GUID + ".doc"; document.Save(tempfilePath, SaveFormat.Doc); SaveAttachment( FilePath: tempfilePath, ApplicationNumber: ContractNumber, TemplateId: TemplateNameID, TemplateName: TemplateName, AttachmentId: GUID, FileName: fileName + ".doc", SchemaCode: ActionContext.SchemaCode, DataField: SavedDataField, BizObjectId: ActionContext.BizObjectID, InstanceType: instanceType, InstanceId: ActionContext.InstanceId, Rate_Fixed: rate_fixed, Rate_Base: rate_base, Rate_Float: rate_float ); if (instanceType.ToString() == "正源") { string tempfilePathPDF = Server.MapPath("~/TempImages/") + GUID + ".pdf"; document.Save(tempfilePathPDF, SaveFormat.Pdf); SaveAttachment( FilePath: tempfilePathPDF, ApplicationNumber: ContractNumber, TemplateId: TemplateNameID, TemplateName: TemplateName, AttachmentId: Guid.NewGuid().ToString(), FileName: fileName + ".pdf", SchemaCode: ActionContext.SchemaCode, DataField: SavedDataField, BizObjectId: ActionContext.BizObjectID, InstanceType: instanceType, InstanceId: ActionContext.InstanceId, Rate_Fixed: rate_fixed, Rate_Base: rate_base, Rate_Float: rate_float ); } #endregion } catch (Exception e) { AppUtility.Engine.LogWriter.Write(e.ToString()); flag = false; message = e.Message; } return(new { Flag = flag, FileName = fileName, Id = GUID, Message = message }); }