/// <summary> /// 操作word通用类 LIYOUMING add 2017-12-27 /// </summary> public class DocHelper { /// <summary> /// 获取模版设计服务数据服务 /// </summary> private static IOccupationDesigner _sqlServices = AutofacWorkContainer.Resolve<IOccupationDesigner>(); /// <summary> /// 拼接组合多个Word文档 /// </summary> /// <param name="filepaths">模版文件多个</param> /// <param name="savepath">保存文件地址</param> public static void BeachReadWord(List<WordSeting> wordSetings, string unitid, out MemoryStream stream) { if (wordSetings == null || wordSetings.Count == 0) { throw new Exception("未设置Word模版"); } //载入第一个模版 Document doc = new Document();//载入模板 doc.RemoveAllChildren(); wordSetings.ForEach(c => { Document srcDoc = ReadWord(c, unitid); srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous; doc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting); }); stream = new MemoryStream(); doc.Save(stream, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(SaveFormat.Docx)); // doc.Save(stream, SaveFormat.Docx); } /// <summary> /// 业务操作 /// </summary> /// <param name="filepath"></param> private static Document ReadWord(WordSeting wordSeting, string unitid) { Document srcDoc = new Document(wordSeting.WordPath); switch (wordSeting.WordType) { case (int)Models.Enum.WordType.Column: InsertPic_Column3D(srcDoc, wordSeting, unitid); break; case (int)Models.Enum.WordType.PIE: InsertPic_Pie3D(srcDoc, wordSeting, unitid); break; case (int)Models.Enum.WordType.Line: InsertPic_Line3D(srcDoc, wordSeting, unitid); break; case (int)Models.Enum.WordType.TEXT: InsertData_Replace(srcDoc, wordSeting, unitid); break; case (int)Models.Enum.WordType.Table: InsertData_Table(srcDoc, wordSeting, unitid); break; case (int)Models.Enum.WordType.HTML: InsertData_HTML(srcDoc, wordSeting, unitid); break; } #region 测试版本呢 //if (typeId == 0) //{ // #region 虚拟化数据 // //DataTable datasource = new DataTable("tb"); // //datasource.Columns.Add("类型"); // //datasource.Columns.Add("已预约"); // //datasource.Columns.Add("体检中"); // //datasource.Columns.Add("已打印"); // //for (int i = 0; i < 3; i++) // //{ // // var row = datasource.NewRow(); // // row["类型"] = "分组" + i; // // row["已预约"] = 5 * (i + 1); // // row["体检中"] = 3 * (i + 1); // // row["已打印"] = 9 * (i + 1); // // datasource.Rows.Add(row); // //} // #endregion // InsertPic_Column3D(srcDoc, wordSeting, unitid); //} //if (typeId == 1) //{ // #region 虚拟化数据 // //DataTable datasource = new DataTable("tb"); // //datasource.Columns.Add("类型"); // //datasource.Columns.Add("已预约"); // //datasource.Columns.Add("体检中"); // //datasource.Columns.Add("已打印"); // //for (int i = 0; i < 1; i++) // //{ // // var row = datasource.NewRow(); // // row["类型"] = "分组" + i; // // row["已预约"] = 5 * (i + 1); // // row["体检中"] = 3 * (i + 1); // // row["已打印"] = 9 * (i + 1); // // datasource.Rows.Add(row); // //} // #endregion // InsertPic_Pie3D(srcDoc, wordSeting, unitid); //} //if (typeId == 2) //{ // #region 虚拟化数据 // //DataTable datasource = new DataTable("tb"); // //datasource.Columns.Add("类型"); // //datasource.Columns.Add("已预约"); // //datasource.Columns.Add("体检中"); // //datasource.Columns.Add("已打印"); // //for (int i = 0; i < 1; i++) // //{ // // var row = datasource.NewRow(); // // row["类型"] = "分组" + i; // // row["已预约"] = 5 * (i + 1); // // row["体检中"] = 3 * (i + 1); // // row["已打印"] = 9 * (i + 1); // // datasource.Rows.Add(row); // //} // #endregion // InsertData_Table(srcDoc, wordSeting, unitid); //} //if (typeId == 3) //{ // #region 虚拟化数据 // //DataTable datasource = new DataTable("tb"); // //datasource.Columns.Add("类型"); // //datasource.Columns.Add("已预约"); // //datasource.Columns.Add("体检中"); // //datasource.Columns.Add("已打印"); // //for (int i = 0; i < 3; i++) // //{ // // var row = datasource.NewRow(); // // row["类型"] = "分组" + i; // // row["已预约"] = 5 * (i + 1); // // row["体检中"] = 3 * (i + 1); // // row["已打印"] = 9 * (i + 1); // // datasource.Rows.Add(row); // //} // #endregion // InsertPic_Line3D(srcDoc, wordSeting, unitid); //} //if (typeId == 4) //{ // #region 虚拟化数据 // //DataTable datasource = new DataTable("tb"); // //datasource.Columns.Add("类型"); // //datasource.Columns.Add("已预约"); // //datasource.Columns.Add("体检中"); // //datasource.Columns.Add("已打印"); // //for (int i = 0; i < 1; i++) // //{ // // var row = datasource.NewRow(); // // row["类型"] = "分组" + i; // // row["已预约"] = 5 * (i + 1); // // row["体检中"] = 3 * (i + 1); // // row["已打印"] = 9 * (i + 1); // // datasource.Rows.Add(row); // //} // ////替换数据处理 // //DataSet ds = new DataSet(); // //ds.Tables.Add(datasource); // #endregion // InsertData_Replace(srcDoc, wordSeting, unitid); //} #endregion return srcDoc; } /// <summary> /// 添加分组列说明 liyouming /// </summary> /// <param name="chart"></param> /// <param name="seriesSize">分组数量</param> /// <param name="lableSize">列组数量</param> private static void SetLable_Column(Chart chart, int seriesSize, int lableSize) { for (int j = 0; j < seriesSize; j++) { ChartDataLabelCollection dataLabelCollection = chart.Series[j].DataLabels; for (int i = 0; i < lableSize; i++) { ChartDataLabel chartDataLabel = dataLabelCollection.Add(i); chartDataLabel.ShowLegendKey = true; chartDataLabel.ShowLeaderLines = true; chartDataLabel.ShowCategoryName = false; //chartDataLabel.ShowPercentage = true; chartDataLabel.ShowSeriesName = true; chartDataLabel.ShowValue = true; chartDataLabel.Separator = " "; } } } /// <summary> /// 设置显示Lable /// </summary> /// <param name="chart"></param> /// <param name="lableSize"></param> private static void SetLable_Pie(Chart chart, int lableSize) { ChartDataLabelCollection dataLabelCollection = chart.Series[0].DataLabels; for (int i = 0; i < lableSize; i++) { ChartDataLabel chartDataLabel = dataLabelCollection.Add(i); chartDataLabel.ShowLegendKey = true; chartDataLabel.ShowLeaderLines = true; chartDataLabel.ShowCategoryName = true; chartDataLabel.ShowPercentage = true; chartDataLabel.ShowSeriesName = false; chartDataLabel.ShowValue = true; chartDataLabel.Separator = " "; } } /// <summary> /// 饼状图 /// </summary> /// <param name="doc"></param> /// <param name="with"></param> /// <param name="height"></param> /// <param name="datasource"></param> private static Document InsertPic_Pie3D(Document doc, WordSeting wordseting, string UinitId) { DataTable datasource = null; if (string.IsNullOrEmpty(wordseting.WordData)) { throw new Exception("Pie图形未设置数据源"); } //获取数据源 datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId).Tables[0]; Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); ChartType imagestype = ChartType.Pie; if (wordseting.ImgageType == 1) { imagestype = ChartType.Pie3D; } Shape shape = builder.InsertChart(imagestype, (double)wordseting.Width, (double)wordseting.Height); shape.Title = wordseting.Title; Chart chart = shape.Chart; ChartSeriesCollection seriesColl = chart.Series; seriesColl.Clear(); //生成word 分组统计图,说明 liyouming add /* ------类型[固定]---series1-----series2------ ------分组名1--------22----------62---------- ---------------------------------------------- */ List<string> lstCategories = new List<string>(); if (datasource != null && datasource.Rows.Count > 0) { List<DataRow> lstRows = new List<DataRow>(); foreach (DataRow row in datasource.Rows) { lstRows.Add(row); } List<double> doub = new List<double>(); foreach (DataColumn col in datasource.Columns) { if (col.ColumnName != "类型") { lstCategories.Add(col.ColumnName); foreach (var datarow in lstRows) { double doubx = 0; double.TryParse(datarow[col.ColumnName] + "", out doubx); doub.Add(doubx); } } } string[] categories = lstCategories.ToArray(); seriesColl.Add(shape.Title, categories, doub.ToArray()); if (wordseting.IfChartLabel == 1) { SetLable_Pie(chart, lstCategories.Count); } } return builder.Document; } /// <summary> /// 柱状分组图 /// </summary> /// <param name="doc"></param> /// <param name="with"></param> /// <param name="height"></param> /// <param name="datasource"></param> private static Document InsertPic_Column3D(Document doc, WordSeting wordseting, string UinitId) { DataTable datasource = null; if (string.IsNullOrEmpty(wordseting.WordData)) { throw new Exception("Column图形未设置数据源"); } //获取数据源 datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId).Tables[0]; Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); ChartType imagestype = ChartType.Column; if (wordseting.ImgageType == 1) { imagestype = ChartType.Column3D; } Shape shape = builder.InsertChart(imagestype, (double)wordseting.Width, (double)wordseting.Height); shape.Title = wordseting.Title; Chart chart = shape.Chart; ChartSeriesCollection seriesColl = chart.Series; seriesColl.Clear(); //生成word 分组统计图,说明 liyouming add /* ------类型[固定]---series1-----series2------ ------分组名1--------22----------62---------- ------分组名2--------88----------33---------- ---------------------------------------------- */ List<string> lstCategories = new List<string>(); if (datasource != null && datasource.Rows.Count > 0) { List<DataRow> lstRows = new List<DataRow>(); foreach (DataRow row in datasource.Rows) { lstCategories.Add(row["类型"] + ""); lstRows.Add(row); } string[] categories = lstCategories.ToArray(); foreach (DataColumn col in datasource.Columns) { if (col.ColumnName != "类型") { List<double> doub = new List<double>(); foreach (var datarow in lstRows) { double doubx = 0; double.TryParse(datarow[col.ColumnName] + "", out doubx); doub.Add(doubx); } seriesColl.Add(col.ColumnName, categories, doub.ToArray()); } } if (wordseting.IfChartLabel == 1) { SetLable_Column(chart, seriesColl.Count, lstCategories.Count); } } return builder.Document; } /// <summary> /// 添加线性图 /// </summary> /// <param name="doc"></param> /// <param name="with"></param> /// <param name="height"></param> /// <param name="datasource"></param> private static Document InsertPic_Line3D(Document doc, WordSeting wordseting, string UinitId) { DataTable datasource = null; if (string.IsNullOrEmpty(wordseting.WordData)) { throw new Exception("Line图形未设置数据源"); } //获取数据源 datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId).Tables[0]; DocumentBuilder builder = new DocumentBuilder(doc); ChartType imagestype = ChartType.Line; if (wordseting.ImgageType == 1) { imagestype = ChartType.Line3D; } Shape shape = builder.InsertChart(imagestype,(double)wordseting.Width, (double)wordseting.Height); shape.Title = wordseting.Title; Chart chart = shape.Chart; ChartSeriesCollection seriesColl = chart.Series; seriesColl.Clear(); List<string> lstCategories = new List<string>(); if (datasource != null && datasource.Rows.Count > 0) { List<DataRow> lstRows = new List<DataRow>(); foreach (DataRow row in datasource.Rows) { lstCategories.Add(row["类型"] + ""); lstRows.Add(row); } string[] categories = lstCategories.ToArray(); foreach (DataColumn col in datasource.Columns) { if (col.ColumnName != "类型") { List<double> doub = new List<double>(); foreach (var datarow in lstRows) { double doubx = 0; double.TryParse(datarow[col.ColumnName] + "", out doubx); doub.Add(doubx); } seriesColl.Add(col.ColumnName, categories, doub.ToArray()); } } if (wordseting.IfChartLabel == 1) { SetLable_Column(chart, seriesColl.Count, 1); } } return builder.Document; } /// <summary> /// 添加统计列表Table /// </summary> /// <param name="doc"></param> /// <param name="with"></param> /// <param name="height"></param> /// <param name="datasource"></param> private static Document InsertData_Table(Document doc, WordSeting wordseting, string UinitId) { DataTable datasource = null; if (string.IsNullOrEmpty(wordseting.WordData)) { throw new Exception("Table未设置数据源"); } //获取数据源 datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId).Tables[0]; DocumentBuilder builder = new DocumentBuilder(doc); builder.Write(" "); if (datasource != null && datasource.Rows.Count > 0) { Table table = builder.StartTable(); foreach (DataColumn col in datasource.Columns) { builder.InsertCell(); table.AutoFit(AutoFitBehavior.FixedColumnWidths); builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; //builder.CellFormat.SetPaddings(5, 5, 5, 5); builder.CellFormat.Width = (double)wordseting.Width; builder.Write(col.ColumnName); } builder.EndRow(); foreach (DataRow row in datasource.Rows) { foreach (DataColumn col in datasource.Columns) { builder.InsertCell(); builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; //builder.CellFormat.SetPaddings(5, 5, 5, 5); builder.CellFormat.Width = (double)wordseting.Width; builder.Write(row[col.ColumnName] + ""); } builder.EndRow(); } builder.EndTable(); } return builder.Document; } /// <summary> /// 添加HTML数据 /// </summary> /// <param name="doc"></param> /// <param name="with"></param> /// <param name="height"></param> /// <param name="datasource"></param> private static Document InsertData_HTML(Document doc, WordSeting wordseting, string UinitId) { DataSet datasource = null; //获取数据源 DocumentBuilder builder = new DocumentBuilder(doc); string htmlConetent = wordseting.WordHtml; //没有数据源就直接插入html内容 if (datasource == null) { } //有数据源把html当作模版写入 这里模版分为类型 else { Regex regtag = new Regex(@"<temp class='TempIndexd*'.*?>.*?</temp>"); MatchCollection colectiontag = regtag.Matches(htmlConetent); datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId); #region TempIndex模版 if (colectiontag.Count > 0) { for (int p = 0; p < colectiontag.Count; p++) { var _sb1 = new StringBuilder(); var temp = colectiontag[p].Value; int tableIndex = 0; int.TryParse(temp.Substring(temp.IndexOf("TempIndex") + 9, 2), out tableIndex); DataTable defaultTabel = datasource.Tables[tableIndex]; if (defaultTabel.Rows.Count > 0) { string tempall = string.Empty; foreach (DataRow row1 in defaultTabel.Rows) { string rowtemp = temp; foreach (DataColumn dc in defaultTabel.Columns) { if (row1[dc.ColumnName] != null && temp.Contains("@" + dc.ColumnName)) { rowtemp = Regex.Replace(rowtemp, "@" + dc.ColumnName, (row1[dc.ColumnName] + "").Replace(" ", "<br/>")); } } _sb1.Append(rowtemp); } htmlConetent = htmlConetent.Replace(temp, _sb1.ToString()); } } } #endregion Regex regtable = new Regex(@"<table class='TableIndexd*'.*?>.*?</table>"); MatchCollection colectiontable = regtable.Matches(htmlConetent); #region TableIndex模版 if (colectiontable.Count > 0) { for (var i = 0; i < colectiontable.Count; i++) { var _sb1 = new StringBuilder(); var temp = colectiontable[i].Value; int tableIndex = 0; int.TryParse(temp.Substring(temp.IndexOf("TableIndex") + 10, 2), out tableIndex); DataTable dt = datasource.Tables[tableIndex]; List<ItemsInfo> dic = new List<ItemsInfo>(); string rowtemp = temp; if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { dic.Add(new ItemsInfo { ProName = row["Name"] + "", ResultVal = row["Value"] + "" }); } } try { Regex tep = new Regex(@"@.*?@"); MatchCollection groupVal = tep.Matches(temp); for (var j = 0; j < groupVal.Count; j++) { var v = groupVal[j].Value; string citem = v.Substring(1, v.Length - 2); var keyVal = dic.Where(x => x.ProName == citem).FirstOrDefault(); if (keyVal != null) { rowtemp = Regex.Replace(rowtemp, v, (keyVal.ResultVal + "").Replace("\r\n", "<br/>").Replace(" ", "<br/>")); } else { rowtemp = Regex.Replace(rowtemp, v, ""); } } _sb1.Append(rowtemp); } catch (Exception e) { } htmlConetent = htmlConetent.Replace(temp, _sb1.ToString()); } } #endregion } builder.InsertHtml(htmlConetent); return builder.Document; } /// <summary> /// 替换文本 /// </summary> /// <param name="doc"></param> /// <param name="datasource"></param> /// <returns></returns> private static Document InsertData_Replace(Document doc, WordSeting wordseting, string UinitId) { DataSet datasource = null; if (string.IsNullOrEmpty(wordseting.WordData)) { throw new Exception("Replace未设置数据源"); } //获取数据源 datasource = _sqlServices.GetWordDataBySql(wordseting.WordData, UinitId); if (datasource != null && datasource.Tables.Count > 0) { foreach (DataTable table in datasource.Tables) { if (table != null && table.Rows.Count == 1) { foreach (DataColumn col in table.Columns) { Regex reg1 = new Regex(@"{" + col.ColumnName + "}"); doc.Range.Replace(reg1, table.Rows[0][col.ColumnName].ToString()); } } else if (table != null) { //这种设计数据源需用 Name Value 处理 foreach (DataRow row in table.Rows) { Regex reg1 = new Regex(@"{" + row["Name"] + "}"); doc.Range.Replace(reg1, row["Value"] + ""); } } } } return doc; } }
通过模版设计处理文档,测试效果