using Lskj.Core; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Lskj.Model; using Lskj.Control; using Lskj.Business.Impl; using Lskj.Business; namespace Lskj.AutoWordFile { public partial class FrmMain : BaseForm { /// /// 基础对象 /// public ModuleModel ModuleModel; /// /// 单据对象 /// public BillModel BillModel; /// /// 调用动态链接库默认传递参数 /// public DynamicAutoWordFile Model; private bool NewInitSuccess = false; private int fileCount; public string modelCound = string.Empty; public string modelName = string.Empty; public DataTable defaultMenuID = null; public FrmMain() { InitializeComponent(); Lskj.Control.Model.AutoSizeChange.ControllInitializeSize(this); } DataTable masterdt = new DataTable(); private void button2_Click(object sender, EventArgs e) { try { //Create word document Document document = new Document(); document.LoadFromFile(@"..\..\bin\Debug\Sample.docx"); //Save the document to a PDF file. document.SaveToFile("Sample.pdf", FileFormat.PDF); //Launching the pdf reader to open. FileViewer("Sample.pdf"); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); //LogUtil.WriteError("朗速-开发设计文档(WORD)智能生成工具 生成pdf失败",ex); //MessageUtil.Show("朗速-开发设计文档(WORD)智能生成工具 生成pdf失败" + ex); } } /// /// 初始化同步平台 /// private void Initialization() { try { RefreshLog(DateTime.Now + "正在初始化平台.\r\n"); if (DBConfig.Instance.CreateConnection()) { SqlHelper.ExecuteNonQuery(string.Format("UPDATE P_SYSTEMTAB SET WORDtAGID=0")); NewInitSuccess = true; RefreshLog(DateTime.Now + "初始化平台成功.\r\n"); //获取指定目录下所有文件数量(实际过程忽略) fileCount = 1; if (Model.Var.Equals("单表") && !string.IsNullOrWhiteSpace(Model.Var)) { this.ModuleModel = new BaseAuditModel(MainImpl.GetSystemdllTab(this.Model.ModuleCode)); if (this.ModuleModel == null || string.IsNullOrEmpty(this.ModuleModel.FormKey)) { MessageUtil.Show("无效的模块编号->" + Model.ModuleCode); this.Close(); } this.modelName = ModuleModel.MenuText; } else if (Model.Var.Equals("单据") && !string.IsNullOrWhiteSpace(Model.Var)) { this.BillModel = new BillModel(BillImpl.GetBillInfo(this.Model.ModuleCode)); if (this.BillModel == null || string.IsNullOrEmpty(this.BillModel.FormKey)) { MessageUtil.Show("无效的模块编号->" + Model.ModuleCode); this.Close(); } this.modelName = BillModel.TypeName; } this.modelCound = this.Model.ModuleCode; //设置进度条基础属性 this.lbl_progress.Value = 0; this.lbl_progress.Style = ProgressBarStyle.Blocks; this.lbl_progress.Maximum = fileCount; this.lbl_progress.Minimum = 0; this.lbl_progress.MarqueeAnimationSpeed = 100; this.lbl_progress.Step = 1; this.lbl_progress.Text = "0%"; this.lbl_progress.Refresh(); } else { RefreshLog(DateTime.Now + " 初始化平台失败.\r\n"); } } catch (Exception ex) { RefreshLog(DateTime.Now + string.Format("初始化失败.原因:{0}.\r\n", ex.Message)); } } /// /// 主线程刷新数据 /// /// public void RefreshLog(string msg) { txtLog.Text += msg; txtLog.Select(txtLog.TextLength, 0); txtLog.ScrollToCaret(); } /// /// 后台线程刷新数据 /// /// public void RefreshLogUIThread(string msg) { Invoke((EventHandler)delegate { txtLog.Text += msg; txtLog.Select(txtLog.TextLength, 0); txtLog.ScrollToCaret(); }); } private void FileViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } } private DataSet Worddata(string modid, int tagid, int mid) { try { SqlParameter[] param = { new SqlParameter("@modid",SqlDbType.VarChar,15), new SqlParameter("@tagid",SqlDbType.Int), new SqlParameter("@Mid",SqlDbType.Int) }; param[0].Value = modid; param[1].Value = tagid; param[2].Value = mid; DataSet ds = SqlHelper.ExecuteDataSet(CommandType.StoredProcedure, "pr_system_File01", "#ba_firstpage", param); return ds; } catch (Exception ex) { throw; } } public void Mulu() { DBConfig.Instance.CreateConnection(); DataTable headerdt = SqlHelper.ExecuteDataTable("select Erp_ItemInfo from p_systemtab");//初始化选择的套用模块 DataTable firstdt = SqlHelper.ExecuteDataTable("select ERP_WORDTitle from p_systemtab");//初始化选择的首页模块 DataTable seconddt = SqlHelper.ExecuteDataTable("select top 1 SubSysName+'-ERP流程' as name from P_SubSystemTab where SubSysId in(select SubSysId from P_FormMenuConfigTab where PurviewId in( select modid from P_ConveWordTmpTab))");//初始化选择的首页模块 RefreshLogUIThread(string.Format("开始生成设计文件:\r\n")); RefreshLogUIThread(string.Format("开始智能生成:.\r\n")); //初始化文档 Document document = new Document(); Section sec0 = document.AddSection(); Section sec1 = document.AddSection(); Section sec = document.AddSection(); //将默认首页样式添加到文档并修改 Style BodyTextStyle = document.AddStyle(BuiltinStyle.Subtitle); BodyTextStyle.CharacterFormat.Font = new System.Drawing.Font("FangSong", 24); BodyTextStyle.CharacterFormat.TextColor = Color.Black; BodyTextStyle.CharacterFormat.Bold = true; //将默认首页样式2添加到文档并修改 Style BodyTextStyle2 = document.AddStyle(BuiltinStyle.BodyText); BodyTextStyle2.CharacterFormat.Font = new System.Drawing.Font("FangSong", 16); BodyTextStyle2.CharacterFormat.TextColor = Color.Black; //将默认标题样式添加到文档并修改 Style titleStyle = document.AddStyle(BuiltinStyle.Title); titleStyle.CharacterFormat.Font = new System.Drawing.Font("Microsoft Yahei", 10); titleStyle.CharacterFormat.TextColor = Color.FromArgb(42, 123, 136); //判断是否为段落样式,然后设置段落格式 if (titleStyle is ParagraphStyle) { ParagraphStyle ps = titleStyle as ParagraphStyle; ps.ParagraphFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Single; ps.ParagraphFormat.Borders.Bottom.Color = Color.FromArgb(42, 123, 136); ps.ParagraphFormat.Borders.Bottom.LineWidth = 1.5f; ps.ParagraphFormat.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; } //应用风格 HeaderFooter header = sec.HeadersFooters.Header; Paragraph paragraph = header.AddParagraph(); sec0.PageSetup.HeaderDistance = 7; sec1.PageSetup.HeaderDistance = 7; sec0.PageSetup.FooterDistance = 7; sec1.PageSetup.FooterDistance = 7; paragraph.AppendText(headerdt.Rows[0]["Erp_ItemInfo"] + ""); paragraph.ApplyStyle(BuiltinStyle.Title); HeaderFooter footer = sec.HeadersFooters.Footer; Paragraph footerPara = footer.AddParagraph(); TextRange TR2 = footerPara.AppendText("地址:中国(四川)自由贸易试验区成都高新区吉泰五路88号 电话:18123296181/028-85379300 "); footerPara.AppendField("页码", Spire.Doc.FieldType.FieldPage); footerPara.AppendText(" of "); footerPara.AppendField("总页数", Spire.Doc.FieldType.FieldNumPages); footerPara.Format.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Single; footerPara.Format.Borders.Top.Color = Color.FromArgb(42, 123, 136); footerPara.Format.Borders.Top.LineWidth = 1.5f; sec.PageSetup.FooterDistance = 7; sec.PageSetup.HeaderDistance = 7; DataTable middt = SqlHelper.ExecuteDataTable(string.Format("select * from P_WordFileSetTab where Mid='{0}'", 0));//初始化选择的套用模块 DataRow midrt = middt.Rows[0]; //添加默认标题1样式 Style heading1Style = document.AddStyle(BuiltinStyle.Heading1); heading1Style.CharacterFormat.Font = new System.Drawing.Font(midrt["TitleFont1"] + "", int.Parse(midrt["TitleFontSize1"] + "")); heading1Style.CharacterFormat.Bold = bool.Parse(midrt["TitleFontBoid1"] + ""); heading1Style.CharacterFormat.TextColor = Color.FromName(midrt["TitleFontColor1"] + ""); //添加默认标题2样式paragraph Style heading2Style = document.AddStyle(BuiltinStyle.Heading2); heading2Style.CharacterFormat.Font = new System.Drawing.Font(midrt["TitleFont2"] + "", int.Parse(midrt["TitleFontSize2"] + "")); heading2Style.CharacterFormat.TextColor = Color.FromName(midrt["TitleFontColor2"] + ""); heading2Style.CharacterFormat.Bold = bool.Parse(midrt["TitleFontBoid2"] + ""); //添加默认标题2样式 Style heading3Style = document.AddStyle(BuiltinStyle.Heading3); heading3Style.CharacterFormat.Font = new System.Drawing.Font(midrt["TitleFont3"] + "", int.Parse(midrt["TitleFontSize3"] + "")); heading3Style.CharacterFormat.TextColor = Color.FromName(midrt["TitleFontColor3"] + ""); heading3Style.CharacterFormat.Bold = bool.Parse(midrt["TitleFontBoid3"] + ""); //添加默认表格标题样式 Style GridHeadStyle = document.AddStyle(BuiltinStyle.Normal); GridHeadStyle.CharacterFormat.Font = new System.Drawing.Font(midrt["GridHeadFont"] + "", int.Parse(midrt["GridHeadFontSize"] + "")); GridHeadStyle.CharacterFormat.Bold = bool.Parse(midrt["GridHeadFontBoid"] + ""); //添加默认文本输出样式 Style textStyle = document.AddStyle(BuiltinStyle.Toc1); textStyle.CharacterFormat.Font = new System.Drawing.Font(midrt["TexFontItalic"] + "", int.Parse(midrt["TextFontSize"] + "")); textStyle.CharacterFormat.Bold = bool.Parse(midrt["Textfontboid"] + ""); textStyle.CharacterFormat.TextColor = Color.FromName(midrt["TextfontColor"] + ""); //列表样式 ListStyle bulletList = new ListStyle(document, ListType.Bulleted); bulletList.Name = "bulletList"; document.ListStyles.Add(bulletList); defaultMenuID = string.IsNullOrEmpty(this.modelCound) ? SqlHelper.ExecuteDataTable("select * from p_wordtmptab") : null; int MenuIdCout = defaultMenuID != null ? defaultMenuID.Rows.Count : 1; for (int j = 0; j < MenuIdCout; j++) { modelCound = defaultMenuID != null ? defaultMenuID.Rows[j]["modid"] + "" : modelCound; for (int i = 1; i < 50; i++) { DataSet ds = Worddata(modelCound, i, 0); for (int a = 0; a < ds.Tables.Count; a++) { DataTable dt = ds.Tables[a]; //去除配置列 if (dt == null || dt.Rows.Count == 0) { continue; } DataTable copydt = dt.Copy(); foreach (DataColumn dc in copydt.Columns) { if (dc.ColumnName.Equals("TABLETYPE") || dc.ColumnName.Equals("TITLENAME") || dc.ColumnName.Equals("TITLECONTENT") || dc.ColumnName.Equals("ROWHEIGHT") || dc.ColumnName.Equals("TITLEIMG") || dc.ColumnName.Equals("fontmodid") || dc.ColumnName.Equals("Cellmerge")) dt.Columns.Remove(dc.ColumnName); } //添加段落和表格 paragraph = sec.AddParagraph(); //判断为文字或图片格式不生成表格 if (copydt.Rows[0]["TABLETYPE"] + "" == "2" || (copydt.Rows[0]["TABLETYPE"] + "" == "3" && copydt.Rows.Count == 1)) { switch (copydt.Rows[0]["TABLETYPE"] + "") { case "2": paragraph.AppendText(copydt.Rows[0]["TITLENAME"] + ""); switch (copydt.Rows[0]["fontmodid"] + "") { case "1": paragraph.ApplyStyle(BuiltinStyle.Heading1); break; case "2": paragraph.ApplyStyle(BuiltinStyle.Heading2); break; case "3": paragraph.ApplyStyle(BuiltinStyle.Heading3); break; case "4": paragraph.ApplyStyle(BuiltinStyle.Toc1); break; } paragraph = sec.AddParagraph(); TextRange tr = paragraph.AppendText(copydt.Rows[0]["TITLECONTENT"] + ""); paragraph.ApplyStyle(BuiltinStyle.Toc1); break; case "3": paragraph.AppendText(copydt.Rows[0]["TITLENAME"] + ""); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; switch (copydt.Rows[0]["fontmodid"] + "") { case "1": paragraph.ApplyStyle(BuiltinStyle.Heading1); break; case "2": paragraph.ApplyStyle(BuiltinStyle.Heading2); break; case "3": paragraph.ApplyStyle(BuiltinStyle.Heading3); break; case "4": paragraph.ApplyStyle(BuiltinStyle.Toc1); break; } paragraph = sec.AddParagraph(); Image _image = Image.FromStream(WebRequest.Create(copydt.Rows[0]["TITLEIMG"] + "").GetResponse().GetResponseStream()); DocPicture picture = paragraph.AppendPicture(_image); break; } continue; } Spire.Doc.Table table = sec.AddTable(true); paragraph.AppendText(copydt.Rows[0]["TITLENAME"] + ""); switch (copydt.Rows[0]["fontmodid"] + "") { case "1": paragraph.ApplyStyle(BuiltinStyle.Heading1); break; case "2": paragraph.ApplyStyle(BuiltinStyle.Heading2); break; case "3": paragraph.ApplyStyle(BuiltinStyle.Heading3); break; case "4": paragraph.ApplyStyle(BuiltinStyle.Toc1); break; } table.TableFormat.LeftIndent = 34; bool TableFlag = false; List ColumnList = new List(); foreach (var name in dt.Columns) { ColumnList.Add(name + ""); } //循环遍历data数组给表格赋值 if (copydt.Rows[0]["TABLETYPE"] + "" == "1") { table.ResetCells(dt.Rows.Count + 1, dt.Columns.Count); // ***************** First Row ************************* TableRow row = table.Rows[0]; row.IsHeader = true; row.Height = 20; //unit: point, 1point = 0.3528 mm row.HeightType = TableRowHeightType.Exactly; row.RowFormat.BackColor = Color.FromName(midrt["GridHeadFontColor"] + "");//设置标题的背景颜色 for (int k = 0; k < ColumnList.Count; k++) { string sh = ColumnList[k].Substring((ColumnList[k].Length > 3 ? ColumnList[k].Length : 3) - 3); bool isShuZi = Regex.IsMatch(sh, @"^\d+$"); row.Cells[k].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p = row.Cells[k].AddParagraph(); p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; if (isShuZi) { ColumnList[k] = ColumnList[k].Substring(0, ColumnList[k].Length - 3); table[0, k].Width = int.Parse(sh); } table[0, k].Paragraphs[0].ApplyStyle(BuiltinStyle.Normal); TextRange txtRange = p.AppendText(ColumnList[k]); txtRange.CharacterFormat.Bold = true; } TableFlag = true; } else { table.ResetCells(dt.Rows.Count, dt.Columns.Count); } for (int r = 0; r < dt.Rows.Count; r++) { TableRow dataRow = TableFlag ? table.Rows[r + 1] : table.Rows[r]; dataRow.Height = 20; dataRow.HeightType = TableRowHeightType.Exactly; dataRow.RowFormat.BackColor = Color.Empty; table.Rows[r].Height = int.Parse(copydt.Rows[r]["ROWHEIGHT"] + ""); for (int c = 0; c < dt.Columns.Count; c++) { string sh = ColumnList[c].Substring((ColumnList[c].Length > 3 ? ColumnList[c].Length : 3) - 3); bool isShuZi = Regex.IsMatch(sh, @"^\d+$"); dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle; dataRow.Cells[c].AddParagraph().AppendText(dt.Rows[r][c] + ""); if (copydt.Rows[r]["TABLETYPE"] + "" == "3" && dt.Rows[r][c].ToString() == "图片") { //查找一个特定字符串 ”Spire.Doc” TextSelection selection = document.FindString("图片", false, true); TextRange range = selection.GetAsOneRange(); //替换字符串 range.Text = ""; table.Rows[r].Cells[c].Paragraphs[0].Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; Image _image = Image.FromStream(WebRequest.Create(copydt.Rows[r]["TITLEIMG"] + "").GetResponse().GetResponseStream()); DocPicture picture = table.Rows[r].Cells[c].Paragraphs[0].AppendPicture(_image); float proportion = (float)(_image.Width) / (float)(_image.Height); picture.Height = int.Parse(copydt.Rows[r]["ROWHEIGHT"] + "") - (float.Parse(copydt.Rows[r]["ROWHEIGHT"] + "") / 7); picture.Width = (float)(int.Parse(copydt.Rows[r]["ROWHEIGHT"] + "") * proportion); } if (isShuZi) { table[r, c].Width = int.Parse(sh); } table[TableFlag ? r + 1 : r, c].Paragraphs[0].ApplyStyle(BuiltinStyle.Toc1); } } //判断是否有合并规则 if (copydt.Columns.Contains("Cellmerge")) { //判断合并规则是否为空 if (string.IsNullOrWhiteSpace(copydt.Rows[0]["Cellmerge"] + "")) continue; try { int Mergedindex = copydt.Rows[0]["Cellmerge"].ToString().IndexOf(":"); string MergedText = copydt.Rows[0]["Cellmerge"].ToString().Substring(0, Mergedindex); string Cellmuster = copydt.Rows[0]["Cellmerge"].ToString().Substring(Mergedindex + 1); string[] CellmusterN = Cellmuster.Trim().TrimEnd(':').Split(':'); string[] Cellmerge = MergedText.Trim().TrimEnd('|').Split('|'); for (int cellNum = 0; cellNum < Cellmerge.Count(); cellNum++) { int start = 0; string[] Ranks = Cellmerge[cellNum].Trim().Split(','); int indexs = Ranks[0].IndexOf("-"); int columnindexs = Ranks[1].IndexOf("-"); int startindex = start = int.Parse(Ranks[0].Substring(0, indexs)); int overindex = int.Parse(Ranks[0].Substring(indexs + 1)); if (TableFlag) { start = startindex += 1; overindex += 1; } int startcolumn = int.Parse(Ranks[1].Substring(0, columnindexs)); int overcolumn = int.Parse(Ranks[1].Substring(columnindexs + 1)); table[start, startcolumn].Paragraphs.Clear(); table[start, startcolumn].AddParagraph().AppendText(CellmusterN[cellNum]); table[start, startcolumn].Paragraphs[0].Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; if (overindex - startindex > 0) { while (overindex - startindex >= 0) { table.ApplyHorizontalMerge(startindex, startcolumn, overcolumn); startindex += 1; } table.ApplyVerticalMerge(startcolumn, start, overindex); } else if (overindex - startindex == 0) { table.ApplyHorizontalMerge(startindex, startcolumn, overcolumn); } } } catch (Exception ex) { MessageUtil.Show("设置合并规则出错请检查:" + ex); } } } } } this.Invoke(new EventHandler(delegate { //更新进度条进度状态,当进度条为跑马灯模式时(ProgressBarStyle.Marquee)不可能调用该方法 this.lbl_progress.PerformStep(); //设置进度百分比 double dCount = fileCount, dProg = this.lbl_progress.Value; this.lbl_progress.Text = ((dProg / dCount) * 100).ToString() + "%"; this.lbl_progress.Refresh(); })); RefreshLogUIThread(string.Format("{0}=========》生成成功.\r\n", modelName)); //Save to docx file. string filePath = modelName + "word文档" + DateTime.Now.ToString("yyyyMMddHHmmss") + "Sample.docx"; Paragraph paraInserted = sec1.AddParagraph(); TextRange textRange = paraInserted.AppendText("目 录"); textRange.CharacterFormat.Bold = true; textRange.CharacterFormat.TextColor = Color.CadetBlue; document.Sections[1].Paragraphs.Insert(0, paraInserted); paraInserted.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; document.Sections[1].Paragraphs[0].AppendTOC(1, 9); document.Sections[1].Paragraphs[0].ApplyStyle(BuiltinStyle.Heading1); //document.UpdateTableOfContents(); //添加首页的字段 Paragraph fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; fristparagraph.AppendText(firstdt.Rows[0]["ERP_WORDTitle"] + "\n"); fristparagraph.AppendText(seconddt.Rows.Count > 0 ? seconddt.Rows[0]["name"] + "" : ""); fristparagraph.ApplyStyle(BuiltinStyle.Subtitle); fristparagraph = sec0.AddParagraph(); fristparagraph = sec0.AddParagraph(); fristparagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; fristparagraph.AppendText("(ERP-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + ")\n\n\n\n\n\n\n\n\n\n\n\n"); fristparagraph.ApplyStyle(BuiltinStyle.BodyText); fristparagraph = sec0.AddParagraph(); fristparagraph.AppendText("初稿"); fristparagraph.ApplyStyle(BuiltinStyle.Subtitle); document.SaveToFile(filePath, FileFormat.Docx); //Launching the MS Word file. WordDocViewer(filePath); } public static void WordDocViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } } /// /// 点击开始生成 /// /// /// private void btn_start_Click(object sender, EventArgs e) { this.Initialization(); // 初始化同步平台 // 创建后台线程 try { Thread backThread = new Thread(Mulu); backThread.IsBackground = true; backThread.Start(); } catch (Exception ex) { throw; } } private void btn_getout_Click(object sender, EventArgs e) { this.Close(); } } }