using Spire.Doc; using Spire.Doc.Collections; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; namespace Lskj.AutoCreatWord { public static class CreateWordUtil { /// /// 数据查询对象 /// public static Data.ADO.Abstract.AdsOperater DbOperator; public static bool Create(string mainTempPath, string menuTempPath, string menuTempArray, List dataSets, string savePath, string OAUrl, out string msg, bool createPdf = false) { msg = ""; bool result; try { Document saveDocument = new Document(); foreach (DataSet dataSet in dataSets) { Section firstSection = null; bool hasMainTemp = false; CreateWordUtil.InitTempDocuemnt(saveDocument, mainTempPath, menuTempPath, menuTempArray, dataSet, ref firstSection, ref hasMainTemp); CreateWordUtil.InitCreatBaseSql(saveDocument, dataSet, OAUrl); CreateWordUtil.InitCreatBaseSqlDetail(saveDocument, dataSet, OAUrl); CreateWordUtil.InitCreatTabSql(saveDocument, dataSet, OAUrl); CreateWordUtil.InitCreatTabSqlDetail(saveDocument, dataSet, OAUrl); CreateWordUtil.RemoveTableRow(saveDocument); if (hasMainTemp && firstSection != null) { firstSection.PageSetup.DifferentFirstPageHeaderFooter = true; } } bool flag = !Directory.Exists(Path.GetDirectoryName(savePath)); if (flag) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } string fileName = Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + ".pdf"; saveDocument.SaveToFile(savePath, FileFormat.Doc); if (createPdf) { Document savePDFDoc = new Document(); savePDFDoc.LoadFromFile(savePath); savePDFDoc.SaveToFile(fileName, FileFormat.PDF); } result = true; saveDocument.Close(); saveDocument.Dispose(); msg += "生成成功"; } catch (Exception ex) { msg += "生成失败\r\n" + ex.Message + "\r\n"; result = false; } return result; } private static Document InitTempDocuemnt(Document document, string mainTempPath, string menuTempPath, string menuTempArray, DataSet dataSet, ref Section firstSection, ref bool hasMainTemp) { if (document == null) { document = new Document(); } try { firstSection = null; if (!string.IsNullOrEmpty(mainTempPath) && File.Exists(mainTempPath)) { Section mainSection = new Section(document); firstSection = mainSection; mainSection.PageSetup.DifferentFirstPageHeaderFooter = false; document.Sections.Add(mainSection); hasMainTemp = true; Document document2 = new Document(); document2.LoadFromFile(mainTempPath); foreach (Section section in document2.Sections) { mainSection.PageSetup.Orientation = section.PageSetup.Orientation; mainSection.PageSetup.PageSize = section.PageSetup.PageSize; mainSection.PageSetup.Margins = section.PageSetup.Margins; CpoyHeaderFooter(section, mainSection, HeaderFooterType.FooterEven); CpoyHeaderFooter(section, mainSection, HeaderFooterType.FooterFirstPage); CpoyHeaderFooter(section, mainSection, HeaderFooterType.FooterOdd); CpoyHeaderFooter(section, mainSection, HeaderFooterType.HeaderEven); CpoyHeaderFooter(section, mainSection, HeaderFooterType.HeaderFirstPage); CpoyHeaderFooter(section, mainSection, HeaderFooterType.HeaderOdd); foreach (DocumentObject childObject in section.Body.ChildObjects) { mainSection.Body.ChildObjects.Add(childObject.Clone()); } } } else { Section mainSection = new Section(document); mainSection.PageSetup.DifferentFirstPageHeaderFooter = false; document.Sections.Add(mainSection); } if (!string.IsNullOrEmpty(menuTempPath) && File.Exists(menuTempPath)) { Document document3 = new Document(); document3.LoadFromFile(menuTempPath); if (!string.IsNullOrEmpty(menuTempArray)) { List ModelStr = menuTempArray.Split(',').ToList(); List AddStrList = new List(); for (int i = 0; i < ModelStr.Count; i++) { string moduleIdStr = ModelStr[i]; string index = ""; int order = 0; if (moduleIdStr.Length == 8 && moduleIdStr.StartsWith("XMBG", StringComparison.OrdinalIgnoreCase)) { index = moduleIdStr.Substring(4, 4); AddStrList.Add(moduleIdStr); order = AddStrList.Count(n => n.Equals(moduleIdStr)); if (dataSet.Tables.Count >= 2) { DataTable dataTable = dataSet.Tables[1]; if (dataTable.Columns.Contains("crm_lco_xmbg") && dataTable.Columns.Contains("crm_lco_order")) { var selectRows = dataTable.Rows.Cast().Where(n => (n["crm_lco_xmbg"] + "").Equals(ModelStr[i]) && (n["crm_lco_order"] + "").Equals(order + "")); if (selectRows != null) { foreach (DataRow item in selectRows) { if ((item["crm_lco_xmbg"] + "").Equals(ModelStr[i]) && (item["crm_lco_order"] + "").Equals(order + "")) { item["crm_lco_xmbg"] = $"XMBG_{order}_{index}"; } } } } } } // 在菜单模板中找到对应的 start 和 end 标记 string[] moduleIdWithPms = moduleIdStr.Split('_'); string moduleId = moduleIdWithPms[0]; string isBreakPage = moduleIdWithPms.Length > 1 ? moduleIdWithPms[1] : ""; TextSelection startSelection = document3.FindString("{" + moduleId + ":start}", false, true); TextSelection endSelection = document3.FindString("{" + moduleId + ":end}", false, true); if (startSelection != null && endSelection != null) { if (moduleId.Equals("yw", StringComparison.OrdinalIgnoreCase)) { Paragraph lastBreakParagraph = null; DocumentObject lastBreak = null; foreach (Paragraph paragraph in document.LastSection.Paragraphs) { foreach (DocumentObject docObject in paragraph.ChildObjects) { if (docObject.DocumentObjectType == DocumentObjectType.Break) { Break breakObject = docObject as Break; if (breakObject.BreakType == BreakType.PageBreak) { lastBreakParagraph = paragraph; lastBreak = docObject; } } } } if (lastBreakParagraph != null && lastBreak != null) { lastBreakParagraph.ChildObjects.Remove(lastBreak); } } Section section = startSelection.GetAsOneRange().OwnerParagraph.OwnerTextBody.Owner as Section; if (section.PageSetup.Orientation != document.LastSection.PageSetup.Orientation) { document.LastSection.Paragraphs[document.LastSection.Paragraphs.Count - 1].InsertSectionBreak(SectionBreakType.NoBreak); document.LastSection.PageSetup.Orientation = section.PageSetup.Orientation; document.LastSection.PageSetup.PageSize = section.PageSetup.PageSize; document.LastSection.PageSetup.Margins = section.PageSetup.Margins; } Section lastSection = document.LastSection; if (!moduleId.Equals("yw", StringComparison.OrdinalIgnoreCase)) { if (firstSection != null) { CpoyHeaderFooter(firstSection, section, HeaderFooterType.FooterEven); CpoyHeaderFooter(firstSection, section, HeaderFooterType.FooterOdd); CpoyHeaderFooter(firstSection, section, HeaderFooterType.HeaderEven); CpoyHeaderFooter(firstSection, section, HeaderFooterType.HeaderOdd); } } bool isCopying = false; foreach (DocumentObject obj in section.Body.ChildObjects) { if (obj == startSelection.GetAsOneRange().OwnerParagraph) { isCopying = true; continue; //跳过开始标记 } if (obj == endSelection.GetAsOneRange().OwnerParagraph) { break; //停止复制 } if (isCopying) { DocumentObject documentObject = obj.Clone(); //将内容添加到可替换模板 lastSection.Body.ChildObjects.Add(documentObject); } } } if (moduleIdStr.Length == 8 && moduleIdStr.StartsWith("XMBG", StringComparison.OrdinalIgnoreCase)) { document.ReplaceTextRange(moduleIdStr, $"XMBG_{order}_{index}", false, true); document.Replace(moduleIdStr, $"XMBG_{order}_{index}", false, true); } } } } else { hasMainTemp = false; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return document; } private static void InitCreatBaseSql(Document document, DataSet dataSet, string OAUrl) { for (int i = 0; i < dataSet.Tables.Count; i++) { string data = $"Data{i + 1}"; DataTable dataTable = dataSet.Tables[i]; foreach (DataColumn dataColumn in dataSet.Tables[i].Columns) { DataRow dataRow = dataTable.Rows.Count > 0 ? dataTable.Rows[0] : null; string speciesItem = "!{" + data + "." + dataColumn + "}"; TextSelection[] speciesContains = document.FindAllString(speciesItem, false, true); //bool speciesContains = document.Replace(speciesItem, speciesItem, false, true) > 0; if (speciesContains?.Length > 0) { if ((dataRow[dataColumn] + "").Equals("/")) { document.ReplaceTextRange(speciesItem, "!/", false, true); document.Replace(speciesItem, "!/", false, true); } else { document.ReplaceTextRange(speciesItem, dataRow[dataColumn] + "", false, true); document.Replace(speciesItem, dataRow[dataColumn] + "", false, true); } } string item = "{" + data + "." + dataColumn + "}"; // 替换文档中的占位符 TextSelection[] contains = document.FindAllString(item, false, true); //bool contains = document.Replace(item, item, false, true) > 0; if (contains?.Length > 0)//基础数据直接替换 { if (dataRow != null) { if (dataColumn.ColumnName.Contains("img_"))//单行替换图片 { Image image = null; Size size = new Size(200, 200); string picUrl = dataRow[dataColumn] + ""; if (picUrl.StartsWith("@") && DbOperator != null) { DataTable picTable = DbOperator.ExecuteDataTable(picUrl.TrimStart('@')); if (picTable != null && picTable.Rows.Count > 0) { DataRow picRow = picTable.Rows[0]; string path = picRow.Table.Columns.Contains("value") ? picRow["value"] + "" : ""; int width = picRow.Table.Columns.Contains("width") && int.TryParse(picRow["width"] + "", out width) ? width : 200; int height = picRow.Table.Columns.Contains("height") && int.TryParse(picRow["height"] + "", out height) ? height : 200; size = new Size(width, height); image = InitCreatImage(path, OAUrl); } } else { image = InitCreatImage(picUrl, OAUrl); if (image == null) { image = Base64ToImage(dataRow[dataColumn] + ""); } } // 定位到占位符的位置并替换为图片 TextSelection[] selections = document.FindAllString(item, false, true); foreach (TextSelection selection in selections) { if (image != null) { DocPicture picture = new DocPicture(document); picture.LoadImage(image); picture.Width = size.Width; picture.Height = size.Height; // 用图片替换占位符 TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; int index = paragraph.ChildObjects.IndexOf(range); paragraph.ChildObjects.Remove(range); paragraph.ChildObjects.Insert(index, picture); } else { // 用图片替换占位符 TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; int index = paragraph.ChildObjects.IndexOf(range); paragraph.ChildObjects.Remove(range); } } } else if (dataColumn.ColumnName.Contains("img1_")) { // 定位到占位符的位置并替换为图片 TextSelection[] selections = document.FindAllString(item, false, true); foreach (TextSelection selection in selections) { TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; if (paragraph.OwnerTextBody.Owner is Spire.Doc.Fields.TextBox) { Spire.Doc.Fields.TextBox textBox = (Spire.Doc.Fields.TextBox)paragraph.OwnerTextBody.Owner; textBox.Format.InternalMargin.All = 0; Image image = InitCreatImage(dataRow[dataColumn] + "", OAUrl); if (image == null) { image = Base64ToImage(dataRow[dataColumn] + ""); } if (image != null) { Paragraph lastParagraph = GeObjectParagraph(document, textBox); lastParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; DocPicture picture = lastParagraph.AppendPicture(image); picture.Width = (int)textBox.Width; picture.Height = (int)textBox.Height; picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText; picture.TextWrappingType = TextWrappingType.Both; picture.HorizontalPosition = textBox.HorizontalPosition; picture.VerticalPosition = textBox.VerticalPosition; lastParagraph.ChildObjects.Remove(textBox); } else { Paragraph lastParagraph = GeObjectParagraph(document, textBox); if (lastParagraph != null) { lastParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; lastParagraph.ChildObjects.Remove(textBox); } } } } } else { document.ReplaceTextRange(item, dataRow[dataColumn] + "", false, true); document.Replace(item, dataRow[dataColumn] + "", false, true); } } else { document.ReplaceTextRange(item, "", false, true); document.Replace(item, "", false, true); } } } } } private static void InitCreatBaseSqlDetail(Document document, DataSet dataSet, string OAUrl) { if (dataSet.Tables.Count < 2) { return; } DataTable detailTab = dataSet.Tables[1]; if (detailTab.Rows.Count > 0 && detailTab.Columns.Contains("crm_lco_xmbg")) { DataTable distinctTable = detailTab.AsEnumerable().GroupBy(row => row["crm_lco_xmbg"] + "").Select(group => group.First()).CopyToDataTable(); foreach (DataRow dataRow in distinctTable.Rows) { string pargTag = dataRow["crm_lco_xmbg"] + ""; foreach (DataColumn dataColumn in distinctTable.Columns) { string speciesItem = "!{" + pargTag + "." + dataColumn + "}"; //bool speciesContains = document.Replace(speciesItem, speciesItem, false, true) > 0; TextSelection[] speciesContains = document.FindAllString(speciesItem, false, true); if (speciesContains?.Length > 0) { if ((dataRow[dataColumn] + "").Equals("/")) { document.ReplaceTextRange(speciesItem, "!/", false, true); document.Replace(speciesItem, "!/", false, true); } else { document.ReplaceTextRange(speciesItem, dataRow[dataColumn] + "", false, true); document.Replace(speciesItem, dataRow[dataColumn] + "", false, true); } } string item = "{" + pargTag + "." + dataColumn + "}"; // 替换文档中的占位符 //bool contains = document.Replace(item, item, false, true) > 0; TextSelection[] contains = document.FindAllString(item, false, true); if (contains?.Length > 0)//基础数据直接替换 { if (dataColumn.ColumnName.Contains("img_"))//单行替换图片 { Image image = null; Size size = new Size(200, 200); string picUrl = dataRow[dataColumn] + ""; if (picUrl.StartsWith("@") && DbOperator != null) { DataTable picTable = DbOperator.ExecuteDataTable(picUrl.TrimStart('@')); if (picTable != null && picTable.Rows.Count > 0) { DataRow picRow = picTable.Rows[0]; string path = picRow.Table.Columns.Contains("value") ? picRow["value"] + "" : ""; int width = picRow.Table.Columns.Contains("width") && int.TryParse(picRow["width"] + "", out width) ? width : 200; int height = picRow.Table.Columns.Contains("height") && int.TryParse(picRow["height"] + "", out height) ? height : 200; size = new Size(width, height); image = InitCreatImage(path, OAUrl); } } else { image = InitCreatImage(picUrl, OAUrl); if (image == null) { image = Base64ToImage(dataRow[dataColumn] + ""); } } // 定位到占位符的位置并替换为图片 TextSelection[] selections = document.FindAllString(item, false, true); foreach (TextSelection selection in selections) { if (image != null) { DocPicture picture = new DocPicture(document); picture.LoadImage(image); picture.Width = size.Width; picture.Height = size.Height; // 用图片替换占位符 TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; int index = paragraph.ChildObjects.IndexOf(range); paragraph.ChildObjects.Remove(range); paragraph.ChildObjects.Insert(index, picture); } } } else if (dataColumn.ColumnName.Contains("img1_")) { // 定位到占位符的位置并替换为图片 TextSelection[] selections = document.FindAllString(item, false, true); foreach (TextSelection selection in selections) { TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; if (paragraph.OwnerTextBody.Owner is Spire.Doc.Fields.TextBox) { Spire.Doc.Fields.TextBox textBox = (Spire.Doc.Fields.TextBox)paragraph.OwnerTextBody.Owner; textBox.Format.InternalMargin.All = 0; Image image = InitCreatImage(dataRow[dataColumn] + "", OAUrl); if (image == null) { image = Base64ToImage(dataRow[dataColumn] + ""); } if (image != null) { Paragraph lastParagraph = GeObjectParagraph(document, textBox); lastParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; DocPicture picture = lastParagraph.AppendPicture(image); picture.Width = (int)textBox.Width; picture.Height = (int)textBox.Height; picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText; picture.TextWrappingType = TextWrappingType.Both; picture.HorizontalPosition = textBox.HorizontalPosition; picture.VerticalPosition = textBox.VerticalPosition; lastParagraph.ChildObjects.Remove(textBox); } } } } else { document.ReplaceTextRange(item, dataRow[dataColumn] + "", false, true); document.Replace(item, dataRow[dataColumn] + "", false, true); } } } } } } private static void InitCreatTabSql(Document document, DataSet dataSet, string OAUrl) { // word表格集合 Dictionary> disMergeDic = new Dictionary>(); List targetTables = new List(); string pattern = @"^(?!L)\{#data\d+\.(?!img_)\w+}$"; // 正则表达式匹配 {#data1.xxxxx} string pattern1 = @"^(?!L)\{!#data\d+\.(?!img_)\w+}$"; // 正则表达式匹配 {!#data1.xxxxx} foreach (Section section in document.Sections) { foreach (Table table in section.Tables) { // 检查第一行第一列的值是否符合模式 bool isBreak = false; foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { //if (disMergeDic.ContainsKey(table)) //{ // disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); //} //else //{ // disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); //} continue; } if (string.IsNullOrEmpty(tableCell.Paragraphs[0].Text)) { //if (disMergeDic.ContainsKey(table)) //{ // disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); //} //else //{ // disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); //} continue; } if (Regex.IsMatch(tableCell.Paragraphs[0].Text, pattern, RegexOptions.IgnoreCase) || Regex.IsMatch(tableCell.Paragraphs[0].Text, pattern1, RegexOptions.IgnoreCase)) { string npattern = @"\{!#data(\d+)\.\w+\}"; Match nmatch = Regex.Match(tableCell.Paragraphs[0].Text, npattern, RegexOptions.IgnoreCase); if (nmatch.Success) { if (disMergeDic.ContainsKey(table)) { disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); } else { disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); } tableCell.Paragraphs[0].Text = tableCell.Paragraphs[0].Text.Replace("!#", "#"); } if (!isBreak) { GridTarGet gridTarGet = new GridTarGet(); string patterner = @"\{#data(\d+)\.\w+\}"; Match match = Regex.Match(tableCell.Paragraphs[0].Text, patterner, RegexOptions.IgnoreCase); if (match.Success) { gridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } gridTarGet.targetSection = section; gridTarGet.targetTable = table; gridTarGet.rowIndex = tableRow.GetRowIndex(); targetTables.Add(gridTarGet); // 添加到集合中 isBreak = true; } } } } } } foreach (GridTarGet gridTar in targetTables)//循环整理好的替换表格类 { try { if (int.TryParse(gridTar.number, out int gridTarNum) && dataSet.Tables.Count < gridTarNum) { break; } DataTable dataTable = dataSet.Tables[gridTarNum - 1];//当前表需要用到的数据源 Section section = gridTar.targetSection; Table table = gridTar.targetTable; // 从表格的第一行获取列名 List columnNames = new List(); foreach (TableCell cell in table.Rows[gridTar.rowIndex].Cells) { // 使用正则表达式匹配并提取xxxxx部分 if (cell.Paragraphs.Count == 0) { continue; } Match match = Regex.Match(cell.Paragraphs[0].Text, @"\{#data\d+\.(\w+)\}", RegexOptions.IgnoreCase); if (match.Success) { columnNames.Add(match.Groups[1].Value); // 添加匹配到的xxxxx部分到集合中 } } for (int i = 0; i < dataTable.Rows.Count; i++) { DataRow dataRow = dataTable.Rows[i]; // 在表格中添加新行 TableRow newRow = table.Rows[gridTar.rowIndex].Clone(); table.Rows.Insert(gridTar.rowIndex + i + 1, newRow); // 遍历所有列来填充数据 for (int j = 0; j < columnNames.Count; j++) { // 获取列名,并从数据行中获取相应的数据 if (dataTable.Columns.Contains(columnNames[j])) { Paragraph cloneParagraph = (Paragraph)table.Rows[gridTar.rowIndex].Cells[j].Paragraphs[0].Clone(); CharacterFormat characterFormat = (cloneParagraph.ChildObjects[0] as TextRange).CharacterFormat; ParagraphFormat paragraphFormat = newRow.Cells[j].Paragraphs[0].Format; newRow.Cells[j].Paragraphs.Clear(); newRow.Cells[j].Paragraphs.Add(cloneParagraph); string text = dataRow[columnNames[j]] + ""; string splitPattern = @"\r\n|\r|\n"; // 匹配 CRLF (\r\n), CR (\r), LF (\n) string[] result = Regex.Split(text, splitPattern); cloneParagraph.Text = ""; for (int k = 0; k < result.Length; k++) { string resultText = result[k]; if (k > 0) { Break lineBreak = new Break(document, BreakType.LineBreak); cloneParagraph.ChildObjects.Add(lineBreak); } TextRange textRange = cloneParagraph.AppendText(resultText); textRange.ApplyCharacterFormat(characterFormat); } cloneParagraph.Format.TextAlignment = paragraphFormat.TextAlignment; cloneParagraph.Format.HorizontalAlignment = paragraphFormat.HorizontalAlignment; } } } if (dataTable.Rows.Count > 0) { table.Rows.Remove(table.Rows[gridTar.rowIndex]); } MergeTable(disMergeDic, table, gridTar.rowIndex, gridTar.rowIndex + dataTable.Rows.Count - 1, table.Rows[gridTar.rowIndex].Cells.Count); } catch (Exception) { } } // 表格图片集合 List pictrueTables = new List(); string imgpattern = @"^(?!L)\{#data\d+\.img_\w+}$"; // 正则表达式匹配 {#data1.img_xxxxx} //遍历文档中的所有表格 foreach (Section section in document.Sections) { foreach (Table table in section.Tables) { // 检查第一行第一列的值是否符合模式 bool isImgBreak = false; foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { continue; } string cellText = tableCell.Paragraphs[0].Text; if (Regex.IsMatch(cellText, imgpattern, RegexOptions.IgnoreCase)) { if (!isImgBreak) { GridTarGet gridTarGet = new GridTarGet(); string patterner = @"\{#data(\d+)\.img_\w+\}"; Match match = Regex.Match(cellText, patterner, RegexOptions.IgnoreCase); if (match.Success) { gridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } gridTarGet.targetSection = section; gridTarGet.targetTable = table; gridTarGet.rowIndex = tableRow.GetRowIndex(); pictrueTables.Add(gridTarGet); // 添加到集合中 isImgBreak = true; } } } } } } foreach (GridTarGet gridTar in pictrueTables)//循环整理好的替换表格类 { if (int.TryParse(gridTar.number, out int gridTarNum) && dataSet.Tables.Count < gridTarNum) { break; } DataTable dataTable = dataSet.Tables[gridTarNum - 1];//当前表需要用到的数据源 Section section = gridTar.targetSection; Table table = gridTar.targetTable; // 从表格的第一行获取列名 List columnNames = new List(); foreach (TableCell cell in table.Rows[gridTar.rowIndex].Cells) { // 使用正则表达式匹配并提取xxxxx部分 if (cell.Paragraphs.Count == 0) { continue; } Match match = Regex.Match(cell.Paragraphs[0].Text, @"\{#data\d+\.(img_\w+)\}", RegexOptions.IgnoreCase); if (match.Success) { columnNames.Add(match.Groups[1].Value);//添加匹配到的xxxxx部分到集合中 } } if (dataTable.Rows.Count > 0) { string picUrl = dataTable.Columns.Contains(columnNames[0] + "") ? dataTable.Rows[0][columnNames[0]] + "" : ""; if (!string.IsNullOrWhiteSpace(picUrl)) { List picNameArray = new List(); List picUrlArray = new List(); List picSizeArray = new List(); if (picUrl.StartsWith("@") && DbOperator != null) { DataTable picTable = DbOperator.ExecuteDataTable(picUrl.TrimStart('@')); if (picTable != null) { foreach (DataRow item in picTable.Rows) { try { string name = item.Table.Columns.Contains("name") ? Path.GetFileNameWithoutExtension(item["name"] + "") : ""; string path = item.Table.Columns.Contains("value") ? item["value"] + "" : ""; int width = item.Table.Columns.Contains("width") && int.TryParse(item["width"] + "", out width) ? width : 200; int height = item.Table.Columns.Contains("height") && int.TryParse(item["height"] + "", out height) ? height : 200; Size size = new Size(width, height); picNameArray.Add(name); picUrlArray.Add(path); picSizeArray.Add(size); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } else { picUrlArray = picUrl.TrimEnd(',').Split(',').ToList(); } int rowsCount = picUrlArray.Count; TableRow addRow = null; List addImages = new List(); List addRows = new List(); List afterAddRows = new List(); for (int i = 0; i < table.Rows.Count; i++) { if (i >= gridTar.rowIndex) { addRows.Add(table.Rows[i]); } } for (int i = 1; i <= rowsCount; i++) { Image image = null; string imageUrl = picUrlArray.Count > 0 ? picUrlArray[i - 1] : ""; string imageName = picNameArray.Count > 0 ? picNameArray[i - 1] : ""; Size imageSize = picSizeArray.Count > 0 ? picSizeArray[i - 1] : new Size(200, 200); image = InitCreatImage(imageUrl, OAUrl); if (image == null) { image = Base64ToImage(picUrlArray[i - 1]); } if (image == null) { continue; } if (i % 2 == 1) { afterAddRows = new List(); // 在表格中添加新行 foreach (TableRow item in addRows) { int Index = addRows.IndexOf(item); TableRow newRow = item.Clone(); float totalWidth = 0f; foreach (TableCell cell in newRow.Cells) { totalWidth += cell.Width; } TableCell newCell1 = new TableCell(document); TableCell newCell2 = new TableCell(document); // 设置单元格宽度为原行宽度的一半 newCell1.SetCellWidth(50, CellWidthType.Percentage); newCell1.CellFormat.BackColor = item.Cells[0].CellFormat.BackColor; newCell1.CellFormat.VerticalAlignment = item.Cells[0].CellFormat.VerticalAlignment; newCell2.SetCellWidth(50, CellWidthType.Percentage); newCell2.CellFormat.BackColor = item.Cells[0].CellFormat.BackColor; newCell2.CellFormat.VerticalAlignment = item.Cells[0].CellFormat.VerticalAlignment; newRow.Cells.Clear(); // 将两个新的单元格添加到行中 newRow.Cells.Add(newCell1); newRow.Cells.Add(newCell2); table.Rows.Add(newRow); afterAddRows.Add(newRow); } foreach (TableRow item in afterAddRows) { int addRowIndex = afterAddRows.IndexOf(item); TableRow beforeRow = addRows[addRowIndex]; TableRow newRow = item; int nowIndex = table.Rows.IndexOf(item); if (i % 2 == 1) { if (addRowIndex == 0) { Paragraph paragraph = newRow.Cells[0].AddParagraph(); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; DocPicture picture = paragraph.AppendPicture(image); picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; picture.VerticalAlignment = ShapeVerticalAlignment.Center; picture.Width = imageSize.Width; picture.Height = imageSize.Height; } else if (addRowIndex > 0) { foreach (Paragraph paragraphItem in beforeRow.Cells[0].Paragraphs) { Paragraph newParagraph = (Paragraph)paragraphItem.Clone(); if (!string.IsNullOrEmpty(imageName)) { newParagraph.Text = imageName; } newRow.Cells[0].Paragraphs.Add(newParagraph); } } } if (i == rowsCount) { table.ApplyHorizontalMerge(nowIndex, 0, newRow.Cells.Count - 1); } } } else if (i % 2 == 0 && afterAddRows.Count > 0) { foreach (TableRow item in afterAddRows) { int addRowIndex = afterAddRows.IndexOf(item); TableRow beforeRow = addRows[addRowIndex]; TableRow newRow = item; if (image != null && addRowIndex == 0) { Paragraph paragraph = newRow.Cells[1].AddParagraph(); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; DocPicture picture = paragraph.AppendPicture(image); picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; picture.VerticalAlignment = ShapeVerticalAlignment.Center; picture.Width = imageSize.Width; picture.Height = imageSize.Height; } else if (addRowIndex > 0) { foreach (Paragraph paragraphItem in beforeRow.Cells[0].Paragraphs) { Paragraph newParagraph = (Paragraph)paragraphItem.Clone(); if (!string.IsNullOrEmpty(imageName)) { newParagraph.Text = imageName; } newRow.Cells[1].Paragraphs.Add(newParagraph); } } } } } //if (dataTable.Rows.Count > 0) table.Rows.Remove(table.Rows[gridTar.rowIndex]); for (int i = 0; i < addRows.Count; i++) { table.Rows.Remove(table.Rows[0]); } } else { //地址不存在则删除该表格 section.Body.ChildObjects.Remove(table); //if (table.Rows.Count > 0) //{ // TableRow tableRow = table.Rows[0]; // foreach (TableCell cell in tableRow.Cells) // { // cell.Paragraphs.Clear(); // } //} } string l_imgpattern = @"\{L#data(\d+)\.\w+}"; //正则表达式匹配 {L#data1.img_xxxxx} foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { continue; } string cellText = tableCell.Paragraphs[0].Text; if (Regex.IsMatch(cellText, l_imgpattern, RegexOptions.IgnoreCase)) { GridTarGet sourceGridTarGet = new GridTarGet(); Match match = Regex.Match(cellText, l_imgpattern, RegexOptions.IgnoreCase); if (match.Success) { sourceGridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } sourceGridTarGet.targetTable = table; sourceGridTarGet.rowIndex = tableRow.GetRowIndex(); if (int.TryParse(sourceGridTarGet.number, out int sourceGridTarGetNum) && dataSet.Tables.Count < sourceGridTarGetNum) { break; } DataTable sourceTable = dataSet.Tables[sourceGridTarGetNum - 1];//当前表需要用到的数据源 foreach (DataColumn dataColumn in sourceTable.Columns) { string lastColumn = "{L#Data" + sourceGridTarGet.number + "." + dataColumn + "}"; if (document.FindAllString(lastColumn, false, true)?.Length > 0)//document.Replace(lastColumn, lastColumn, false, true) > 0 { string value = sourceTable.Rows.Count > 0 ? sourceTable.Rows[sourceTable.Rows.Count - 1][dataColumn] + "" : ""; document.ReplaceTextRange(lastColumn, value, false, true); document.Replace(lastColumn, value, false, true); break; } } } } } } } } private static void InitCreatTabSqlDetail(Document document, DataSet dataSet, string OAUrl) { if (dataSet.Tables.Count < 2) { return; } DataTable detailTab = dataSet.Tables[1]; // word表格集合 Dictionary> disMergeDic = new Dictionary>(); Dictionary> mergeDic = new Dictionary>(); List targetTables = new List(); string pattern = @"^(?!L)\{#\w+.(?!img_)\w+}$"; // 正则表达式匹配 {#xxx.xxxxx} string pattern1 = @"^(?!L)\{!#\w+.(?!img_)\w+}$"; // 正则表达式匹配 {!#xxx.xxxxx} foreach (Section section in document.Sections) { foreach (Table table in section.Tables) { // 检查第一行第一列的值是否符合模式 bool isBreak = false; foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { //if (disMergeDic.ContainsKey(table)) //{ // disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); //} //else //{ // disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); //} continue; } if (string.IsNullOrEmpty(tableCell.Paragraphs[0].Text)) { //if (disMergeDic.ContainsKey(table)) //{ // disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); //} //else //{ // disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); //} continue; } if (Regex.IsMatch(tableCell.Paragraphs[0].Text, pattern, RegexOptions.IgnoreCase) || Regex.IsMatch(tableCell.Paragraphs[0].Text, pattern1, RegexOptions.IgnoreCase)) { string npattern = @"\{!#\w+.\w+\}"; Match nmatch = Regex.Match(tableCell.Paragraphs[0].Text, npattern, RegexOptions.IgnoreCase); if (nmatch.Success) { if (disMergeDic.ContainsKey(table)) { disMergeDic[table].Add(tableRow.Cells.IndexOf(tableCell)); } else { disMergeDic.Add(table, new List() { tableRow.Cells.IndexOf(tableCell) }); } tableCell.Paragraphs[0].Text = tableCell.Paragraphs[0].Text.Replace("!#", "#"); } string npattern1 = @"\{#\w+\.(\w+)\}";//匹配合并的列 Match nmatch1 = Regex.Match(tableCell.Paragraphs[0].Text, npattern1, RegexOptions.IgnoreCase); if (nmatch1.Success) { if (mergeDic.ContainsKey(table)) { mergeDic[table].Add($"{{{nmatch1.Groups[1].Value}}}"); } else { mergeDic.Add(table, new List() { $"{{{nmatch1.Groups[1].Value}}}" }); } } if (!isBreak) { GridTarGet gridTarGet = new GridTarGet(); string patterner = @"\{#(\w+)\.\w+\}"; Match match = Regex.Match(tableCell.Paragraphs[0].Text, patterner, RegexOptions.IgnoreCase); if (match.Success) { gridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } gridTarGet.targetTable = table; gridTarGet.rowIndex = tableRow.GetRowIndex(); targetTables.Add(gridTarGet); // 添加到集合中 isBreak = true; } } } } } } foreach (GridTarGet gridTar in targetTables)//循环整理好的替换表格类 { try { DataTable dataTable = detailTab.Clone(); detailTab.Rows.Cast().Where(n => (n["crm_lco_xmbg"] + "").Equals(gridTar.number)).CopyToDataTable(dataTable, LoadOption.OverwriteChanges);//当前表需要用到的数据源 Table table = gridTar.targetTable; if (!disMergeDic.ContainsKey(table) && mergeDic.ContainsKey(table) && mergeDic[table].Count == table.Rows[gridTar.rowIndex].Cells.Count) { GetGroupData(mergeDic, table, ref dataTable); } // 从表格的第一行获取列名 List columnNames = new List(); foreach (TableCell cell in table.Rows[gridTar.rowIndex].Cells) { // 使用正则表达式匹配并提取xxxxx部分 if (cell.Paragraphs.Count == 0) { continue; } Match match = Regex.Match(cell.Paragraphs[0].Text, @"\{#\w+\.(\w+)\}", RegexOptions.IgnoreCase); if (match.Success) { columnNames.Add($"{{{match.Groups[1].Value}}}"); // 添加匹配到的xxxxx部分到集合中 } else { columnNames.Add(cell.Paragraphs[0].Text); } } for (int i = 0; i < dataTable.Rows.Count; i++) { DataRow dataRow = dataTable.Rows[i]; // 在表格中添加新行 TableRow newRow = table.Rows[gridTar.rowIndex].Clone(); table.Rows.Insert(gridTar.rowIndex + i + 1, newRow); // 遍历所有列来填充数据 for (int j = 0; j < columnNames.Count; j++) { string columnName = columnNames[j]; Paragraph sourceParagraph = table.Rows[gridTar.rowIndex].Cells[j].Paragraphs[0]; Paragraph cloneParagraph = (Paragraph)sourceParagraph.Clone(); CharacterFormat characterFormat = (sourceParagraph.ChildObjects[0] as TextRange).CharacterFormat; ParagraphFormat paragraphFormat = newRow.Cells[j].Paragraphs[0].Format; newRow.Cells[j].Paragraphs.Clear(); newRow.Cells[j].Paragraphs.Add(cloneParagraph); if (columnName.StartsWith("{") && columnName.EndsWith("}")) { columnName = columnName.TrimStart('{').TrimEnd('}'); // 获取列名,并从数据行中获取相应的数据 if (dataTable.Columns.Contains(columnName)) { string text = dataRow[columnName] + ""; string splitPattern = @"\r\n|\r|\n"; // 匹配 CRLF (\r\n), CR (\r), LF (\n) string[] result = Regex.Split(text, splitPattern); cloneParagraph.Text = ""; for (int k = 0; k < result.Length; k++) { string resultText = result[k]; if (k > 0) { Break lineBreak = new Break(document, BreakType.LineBreak); cloneParagraph.ChildObjects.Add(lineBreak); } TextRange textRange = cloneParagraph.AppendText(resultText); textRange.ApplyCharacterFormat(characterFormat); } } } else { cloneParagraph.Text = columnName; } cloneParagraph.Format.TextAlignment = paragraphFormat.TextAlignment; cloneParagraph.Format.HorizontalAlignment = paragraphFormat.HorizontalAlignment; } } if (dataTable.Rows.Count > 0) { table.Rows.Remove(table.Rows[gridTar.rowIndex]); } MergeTable(disMergeDic, table, gridTar.rowIndex, gridTar.rowIndex + dataTable.Rows.Count - 1, table.Rows[gridTar.rowIndex].Cells.Count); } catch (Exception ex) { Console.WriteLine(ex.Message); } } // 表格图片集合 List pictrueTables = new List(); string imgpattern = @"^(?!L)\{#\w+\.img_\w+}$"; // 正则表达式匹配 {#data1.img_xxxxx} //遍历文档中的所有表格 foreach (Section section in document.Sections) { foreach (Table table in section.Tables) { // 检查第一行第一列的值是否符合模式 bool isImgBreak = false; foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { continue; } string cellText = tableCell.Paragraphs[0].Text; if (Regex.IsMatch(cellText, imgpattern, RegexOptions.IgnoreCase)) { if (!isImgBreak) { GridTarGet gridTarGet = new GridTarGet(); string patterner = @"\{#(\w+)\.img_\w+\}"; Match match = Regex.Match(cellText, patterner, RegexOptions.IgnoreCase); if (match.Success) { gridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } gridTarGet.targetSection = section; gridTarGet.targetTable = table; gridTarGet.rowIndex = tableRow.GetRowIndex(); pictrueTables.Add(gridTarGet); // 添加到集合中 isImgBreak = true; } } } } } } foreach (GridTarGet gridTar in pictrueTables)//循环整理好的替换表格类 { DataTable dataTable = detailTab.Clone(); detailTab.Rows.Cast().Where(n => (n["crm_lco_xmbg"] + "").Equals(gridTar.number)).CopyToDataTable(dataTable, LoadOption.OverwriteChanges);//当前表需要用到的数据源 Table table = gridTar.targetTable; Section section = gridTar.targetSection; // 从表格的第一行获取列名 List columnNames = new List(); foreach (TableCell cell in table.Rows[gridTar.rowIndex].Cells) { // 使用正则表达式匹配并提取xxxxx部分 if (cell.Paragraphs.Count == 0) { continue; } Match match = Regex.Match(cell.Paragraphs[0].Text, @"\{#\w+\.(img_\w+)\}", RegexOptions.IgnoreCase); if (match.Success) { columnNames.Add(match.Groups[1].Value); // 添加匹配到的xxxxx部分到集合中 } } if (dataTable.Rows.Count > 0) { string picUrl = dataTable.Columns.Contains(columnNames[0] + "") ? dataTable.Rows[0][columnNames[0]] + "" : ""; if (!string.IsNullOrWhiteSpace(picUrl)) { List picNameArray = new List(); List picUrlArray = new List(); List picSizeArray = new List(); if (picUrl.StartsWith("@") && DbOperator != null) { DataTable picTable = DbOperator.ExecuteDataTable(picUrl.TrimStart('@')); if (picTable != null) { foreach (DataRow item in picTable.Rows) { try { string name = item.Table.Columns.Contains("name") ? Path.GetFileNameWithoutExtension(item["name"] + "") : ""; string path = item.Table.Columns.Contains("value") ? item["value"] + "" : ""; int width = item.Table.Columns.Contains("width") && int.TryParse(item["width"] + "", out width) ? width : 200; int height = item.Table.Columns.Contains("height") && int.TryParse(item["height"] + "", out height) ? height : 200; Size size = new Size(width, height); picNameArray.Add(name); picUrlArray.Add(path); picSizeArray.Add(size); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } else { picUrlArray = picUrl.TrimEnd(',').Split(',').ToList(); } int rowsCount = picUrlArray.Count; TableRow addRow = null; List addImages = new List(); List addRows = new List(); List afterAddRows = new List(); for (int i = 0; i < table.Rows.Count; i++) { if (i >= gridTar.rowIndex) { addRows.Add(table.Rows[i]); } } for (int i = 1; i <= rowsCount; i++) { Image image = null; string imageUrl = picUrlArray.Count > 0 ? picUrlArray[i - 1] : ""; string imageName = picNameArray.Count > 0 ? picNameArray[i - 1] : ""; Size imageSize = picSizeArray.Count > 0 ? picSizeArray[i - 1] : new Size(200, 200); image = InitCreatImage(imageUrl, OAUrl); if (image == null) { image = Base64ToImage(picUrlArray[i - 1]); } if (image == null) { continue; } if (i % 2 == 1) { afterAddRows = new List(); // 在表格中添加新行 foreach (TableRow item in addRows) { int Index = addRows.IndexOf(item); TableRow newRow = item.Clone(); float totalWidth = 0f; foreach (TableCell cell in newRow.Cells) { totalWidth += cell.Width; } TableCell newCell1 = new TableCell(document); TableCell newCell2 = new TableCell(document); newCell1.SetCellWidth(50, CellWidthType.Percentage); newCell1.CellFormat.BackColor = item.Cells[0].CellFormat.BackColor; newCell1.CellFormat.VerticalAlignment = item.Cells[0].CellFormat.VerticalAlignment; newCell2.SetCellWidth(50, CellWidthType.Percentage); newCell2.CellFormat.BackColor = item.Cells[0].CellFormat.BackColor; newCell2.CellFormat.VerticalAlignment = item.Cells[0].CellFormat.VerticalAlignment; newRow.Cells.Clear(); // 将两个新的单元格添加到行中 newRow.Cells.Add(newCell1); newRow.Cells.Add(newCell2); table.Rows.Add(newRow); afterAddRows.Add(newRow); } foreach (TableRow item in afterAddRows) { int addRowIndex = afterAddRows.IndexOf(item); TableRow beforeRow = addRows[addRowIndex]; TableRow newRow = item; int nowIndex = table.Rows.IndexOf(item); if (i % 2 == 1) { if (addRowIndex == 0) { Paragraph paragraph = newRow.Cells[0].AddParagraph(); paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center; DocPicture picture = paragraph.AppendPicture(image); picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; picture.VerticalAlignment = ShapeVerticalAlignment.Center; picture.Width = imageSize.Width; picture.Height = imageSize.Height; } else if (addRowIndex > 0) { foreach (Paragraph paragraphItem in beforeRow.Cells[0].Paragraphs) { Paragraph newParagraph = (Paragraph)paragraphItem.Clone(); if (!string.IsNullOrEmpty(imageName)) { newParagraph.Text = imageName; } newRow.Cells[0].Paragraphs.Add(newParagraph); } } } if (i == rowsCount) { table.ApplyHorizontalMerge(nowIndex, 0, newRow.Cells.Count - 1); } } } else if (i % 2 == 0 && afterAddRows.Count > 0) { foreach (TableRow item in afterAddRows) { int addRowIndex = afterAddRows.IndexOf(item); TableRow beforeRow = addRows[addRowIndex]; TableRow newRow = item; if (image != null && addRowIndex == 0) { Paragraph paragraph = newRow.Cells[1].AddParagraph(); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; DocPicture picture = paragraph.AppendPicture(image); picture.HorizontalAlignment = ShapeHorizontalAlignment.Center; picture.VerticalAlignment = ShapeVerticalAlignment.Center; picture.Width = imageSize.Width; picture.Height = imageSize.Height; } else if (addRowIndex > 0) { foreach (Paragraph paragraphItem in beforeRow.Cells[0].Paragraphs) { Paragraph newParagraph = (Paragraph)paragraphItem.Clone(); if (!string.IsNullOrEmpty(imageName)) { newParagraph.Text = imageName; } newRow.Cells[1].Paragraphs.Add(newParagraph); } } } } } //if (dataTable.Rows.Count > 0) table.Rows.Remove(table.Rows[gridTar.rowIndex]); for (int i = 0; i < addRows.Count; i++) { table.Rows.Remove(table.Rows[0]); } } else { //地址不存在则删除该表格 section.Body.ChildObjects.Remove(table); //if (table.Rows.Count > 0) //{ // TableRow tableRow = table.Rows[0]; // foreach (TableCell cell in tableRow.Cells) // { // cell.Paragraphs.Clear(); // } //} } string l_imgpattern = @"\{L#(\w+)\.\w+}"; //正则表达式匹配 {L#data1.img_xxxxx} foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { continue; } string cellText = tableCell.Paragraphs[0].Text; if (Regex.IsMatch(cellText, l_imgpattern, RegexOptions.IgnoreCase)) { GridTarGet sourceGridTarGet = new GridTarGet(); Match match = Regex.Match(cellText, l_imgpattern, RegexOptions.IgnoreCase); if (match.Success) { sourceGridTarGet.number = match.Groups[1].Value; // 捕获组的索引 } sourceGridTarGet.targetTable = table; sourceGridTarGet.rowIndex = tableRow.GetRowIndex(); DataTable sourceTable = detailTab.Clone(); detailTab.Rows.Cast().Where(n => (n["crm_lco_xmbg"] + "").Equals(sourceGridTarGet.number)).CopyToDataTable(sourceTable, LoadOption.OverwriteChanges);//当前表需要用到的数据源 foreach (DataColumn dataColumn in sourceTable.Columns) { string lastColumn = "{L#" + sourceGridTarGet.number + "." + dataColumn + "}"; if (document.FindAllString(lastColumn, false, true)?.Length > 0)//document.Replace(lastColumn, lastColumn, false, true) > 0 { string value = sourceTable.Rows.Count > 0 ? sourceTable.Rows[sourceTable.Rows.Count - 1][dataColumn] + "" : ""; document.ReplaceTextRange(lastColumn, value, false, true); document.Replace(lastColumn, value, false, true); break; } //foreach (TableRow row in table.Rows) //{ // foreach (TableCell cell in row.Cells) // { // foreach (Paragraph paragraph in cell.Paragraphs) // { // if (Regex.IsMatch(paragraph.Text, lastColumn, RegexOptions.IgnoreCase)) // { // string value = dataTable.Rows.Count > 0 ? dataTable.Rows[dataTable.Rows.Count - 1][dataColumn] + "" : ""; // string replaceText = Regex.Replace(paragraph.Text, lastColumn, value, RegexOptions.IgnoreCase); // paragraph.Text = replaceText; // } // } // } //} } } } } } } } /// /// 移除特殊行 /// private static void RemoveTableRow(Document document) { foreach (Section section in document.Sections) { foreach (Table table in section.Tables) { List deleteRows = new List(); foreach (TableRow tableRow in table.Rows) { foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.Paragraphs.Count == 0) { continue; } string cellText = tableCell.Paragraphs[0].Text; if (cellText.Equals("!/")) { deleteRows.Add(tableRow); break; } } } foreach (TableRow tableRow in deleteRows) { int index = tableRow.GetRowIndex(); if (table.Rows.Count > index + 1) { TableRow nextTableRow = table.Rows[index + 1]; foreach (TableCell tableCell in tableRow.Cells) { if (tableCell.CellFormat.VerticalMerge == CellMerge.Start) { List cloneParagraphs = new List(); foreach (Paragraph paragraphItem in tableCell.Paragraphs) { Paragraph newParagraph = (Paragraph)paragraphItem.Clone(); cloneParagraphs.Add(newParagraph); } tableCell.CellFormat.VerticalMerge = CellMerge.None; TableCell nextCell = nextTableRow.Cells[tableCell.GetCellIndex()]; nextCell.CellFormat.VerticalMerge = CellMerge.Start; nextCell.Paragraphs.Clear(); foreach (Paragraph paragraphItem in cloneParagraphs) { nextCell.Paragraphs.Add(paragraphItem); } } } } table.Rows.Remove(tableRow); } } } } /// /// 表格合并 /// private static void MergeTable(Dictionary> disMergeDic, Table table, int contentStartIndex, int contentEndIndex, int colCount) { try { for (int i = 0; i < colCount; i++) { if (disMergeDic.ContainsKey(table) && disMergeDic[table].Contains(i)) { continue; } int startIndex = contentStartIndex; int endIndex = contentEndIndex; for (int j = contentStartIndex; j <= contentEndIndex; j++) { TableRow tableRow = table.Rows[j]; string cellValue = tableRow.Cells[i].Paragraphs.Count > 0 ? tableRow.Cells[i].Paragraphs[0].Text : ""; if (j + 1 <= contentEndIndex) { TableRow nextTableRow = table.Rows[j + 1]; string nextCellValue = nextTableRow.Cells[i].Paragraphs.Count > 0 ? nextTableRow.Cells[i].Paragraphs[0].Text : ""; if (!nextCellValue.Equals(cellValue)) { if (j > startIndex) { for (int start = startIndex + 1; start <= j; start++) { table.Rows[start].Cells[i].Paragraphs.Clear(); } table.ApplyVerticalMerge(i, startIndex, j); } startIndex = j + 1; } } } if (startIndex <= contentEndIndex) { for (int start = startIndex + 1; start <= contentEndIndex; start++) { table.Rows[start].Cells[i].Paragraphs.Clear(); } table.ApplyVerticalMerge(i, startIndex, contentEndIndex); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static Paragraph GeObjectParagraph(Document document, DocumentObject documentObject) { bool isSelect = false; Paragraph lastParagraph = null; //遍历源文档的所有section,检测page break并根据page break拆分文档 foreach (Section sec in document.Sections) { foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj == documentObject && !isSelect) { isSelect = true; } if (obj is Paragraph) { Paragraph para = obj as Paragraph; if (!isSelect) { isSelect = SelectObject(documentObject, para); } if (isSelect) { lastParagraph = para; break; } } else if (obj is Table) { Table table = obj as Table; foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { foreach (Paragraph item in cell.Paragraphs) { if (!isSelect) { isSelect = SelectObject(documentObject, item); } if (isSelect) { lastParagraph = item; break; } } if (isSelect) { break; } } if (isSelect) { break; } } if (isSelect) { break; } } } if (lastParagraph != null) { break; } } return lastParagraph; } private static bool SelectObject(DocumentObject documentObject, Paragraph paragraph) { bool result = false; foreach (object obj in paragraph.ChildObjects) { DocumentObject documentObject2 = (DocumentObject)obj; bool flag = documentObject2 == documentObject; if (flag) { result = true; break; } } return result; } private static Image InitCreatImage(string imagePath, string OAUrl, int width = 0, int height = 0) { string downUrl = ""; try { if (string.IsNullOrEmpty(imagePath)) { return null; } WebClient webClient = new WebClient(); downUrl = imagePath = !imagePath.StartsWith("http") ? OAUrl + imagePath : imagePath; byte[] imageData = webClient.DownloadData(imagePath); using (MemoryStream imageStream = new MemoryStream(imageData)) { Image image = Image.FromStream(imageStream); if (width == 0) width = image.Width; if (height == 0) height = image.Height; //获取图片宽度 int sourceWidth = image.Width; //获取图片高度 int sourceHeight = image.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; //计算宽度的缩放比例 nPercentW = ((float)width / (float)sourceWidth); //计算高度的缩放比例 nPercentH = ((float)height / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; //期望的宽度 int destWidth = (int)(sourceWidth * nPercent); //期望的高度 int destHeight = (int)(sourceHeight * nPercent); Bitmap bitmap = new Bitmap(width, height); Graphics graphics = Graphics.FromImage(bitmap); graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //绘制图像 graphics.DrawImage(image, 0, 0, destWidth, destHeight); graphics.Dispose(); return bitmap; } } catch (Exception ex) { return null; //throw new Exception(string.Format("获取图片{0}失败,原因:{1}\r\n", downUrl, ex.Message)); } } /// /// 复制页眉页脚 /// /// /// /// /// private static void CpoyHeaderFooter(Section sourceSection, Section targetSection, HeaderFooterType headerFooterType) { HeaderFooter headerFooter = sourceSection.HeadersFooters[headerFooterType]; if (headerFooter != null && headerFooter.ChildObjects != null && headerFooter.ChildObjects.Count > 0) { //targetSection.HeadersFooters[headerFooterType].LinkToPrevious = true; targetSection.HeadersFooters[headerFooterType].ChildObjects.Clear(); foreach (DocumentObject obj in headerFooter.ChildObjects) { targetSection.HeadersFooters[headerFooterType].ChildObjects.Add(obj.Clone()); } } } /// /// base64字符串转图片 /// /// /// private static Image Base64ToImage(string base64String) { Image image = null; try { if (!string.IsNullOrEmpty(base64String)) { string pattern = @".*;base64,"; base64String = Regex.Replace(base64String, pattern, ""); byte[] imageBytes = Convert.FromBase64String(base64String); using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { ms.Write(imageBytes, 0, imageBytes.Length); image = Image.FromStream(ms, true); } } } catch (Exception) { } return image; } /// /// 替换值 /// /// /// /// private static void ReplaceTextRange(this Document document, string searchText, string replaceText, bool caseSensitive, bool wholeWord) { // 查找所有匹配 TextSelection[] results = document.FindAllString(searchText, caseSensitive, wholeWord); if (results == null) return; foreach (TextSelection selection in results) { TextRange textRange = selection.GetAsOneRange(); if (textRange != null) { textRange.Text = Regex.Replace(textRange.Text, Regex.Escape(searchText), replaceText, RegexOptions.IgnoreCase); string text = textRange.Text; string splitPattern = @"\r\n|\r|\n"; // 匹配 CRLF (\r\n), CR (\r), LF (\n) string[] result = Regex.Split(text, splitPattern); if (result.Length > 1 && textRange.OwnerParagraph != null) { Paragraph paragraph = textRange.OwnerParagraph; CharacterFormat characterFormat = textRange.CharacterFormat; paragraph.Text = ""; for (int k = 0; k < result.Length; k++) { string resultText = result[k]; if (k > 0) { Break lineBreak = new Break(document, BreakType.LineBreak); paragraph.ChildObjects.Add(lineBreak); } TextRange range = paragraph.AppendText(resultText); range.ApplyCharacterFormat(characterFormat); } } } } } /// /// 获取分组后数据 /// private static void GetGroupData(Dictionary> mergeDic, Table table, ref DataTable dataTable) { try { bool groupSuccess = true; DataTable selectTable = new DataTable(); foreach (string item in mergeDic[table]) { string columnName = item.Trim('{', '}'); if (dataTable.Columns.Contains(columnName)) { selectTable.Columns.Add(dataTable.Columns[columnName].ColumnName, dataTable.Columns[columnName].DataType); } else { groupSuccess = false; break; } } if (groupSuccess) { foreach (DataRow sourceRow in dataTable.Rows) { DataRow dataRow = selectTable.NewRow(); foreach (DataColumn dataColumn in dataRow.Table.Columns) { dataRow[dataColumn] = sourceRow[dataColumn.ColumnName]; } selectTable.Rows.Add(dataRow); } List columns = new List(); foreach (DataColumn item in selectTable.Columns) { columns.Add(item.ColumnName); } // 动态定义要分组的列 string[] groupByColumns = columns.ToArray(); string separator = Guid.NewGuid().ToString().ToLower().Replace("-", ""); // 使用 LINQ 按动态列进行分组 var groupedData = selectTable.AsEnumerable() .GroupBy(row => new { // 动态选择分组键 Key = string.Join(separator, groupByColumns.Select(col => row.Field(col))) }) .Select(g => new { Key = g.Key }); // 创建新的 DataTable 用于存储分组结果 DataTable groupedTable = selectTable.Clone(); foreach (var group in groupedData) { // 将动态键拆分成各个部分,并添加到新行 object[] keyParts = Regex.Split(group.Key.Key, separator); DataRow newRow = groupedTable.NewRow(); for (int i = 0; i < keyParts.Length; i++) { newRow[groupByColumns[i]] = keyParts[i]; } groupedTable.Rows.Add(newRow); } dataTable = groupedTable; } } catch (Exception) { } } /// ///word表格数据配置的集合 /// protected class GridTarGet { public string number; public Section targetSection; public Table targetTable; public int rowIndex; } } }