Aspose.Words 自定义文档模版生成操作类
生活随笔
收集整理的這篇文章主要介紹了
Aspose.Words 自定义文档模版生成操作类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/// <summary>/// 操作word通用類 LIYOUMING add 2017-12-27 /// </summary>public class DocHelper{/// <summary>/// 獲取模版設(shè)計(jì)服務(wù)數(shù)據(jù)服務(wù)/// </summary>private static IOccupationDesigner _sqlServices = AutofacWorkContainer.Resolve<IOccupationDesigner>();/// <summary>/// 拼接組合多個(gè)Word文檔/// </summary>/// <param name="filepaths">模版文件多個(gè)</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("未設(shè)置Word模版");}//載入第一個(gè)模版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>/// 業(yè)務(wù)操作/// </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 測(cè)試版本呢//if (typeId == 0)//{// #region 虛擬化數(shù)據(jù)// //DataTable datasource = new DataTable("tb");// //datasource.Columns.Add("類型");// //datasource.Columns.Add("已預(yù)約");// //datasource.Columns.Add("體檢中");// //datasource.Columns.Add("已打印");// //for (int i = 0; i < 3; i++)// //{// // var row = datasource.NewRow();// // row["類型"] = "分組" + i;// // row["已預(yù)約"] = 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 虛擬化數(shù)據(jù)// //DataTable datasource = new DataTable("tb");// //datasource.Columns.Add("類型");// //datasource.Columns.Add("已預(yù)約");// //datasource.Columns.Add("體檢中");// //datasource.Columns.Add("已打印");// //for (int i = 0; i < 1; i++)// //{// // var row = datasource.NewRow();// // row["類型"] = "分組" + i;// // row["已預(yù)約"] = 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 虛擬化數(shù)據(jù)// //DataTable datasource = new DataTable("tb");// //datasource.Columns.Add("類型");// //datasource.Columns.Add("已預(yù)約");// //datasource.Columns.Add("體檢中");// //datasource.Columns.Add("已打印");// //for (int i = 0; i < 1; i++)// //{// // var row = datasource.NewRow();// // row["類型"] = "分組" + i;// // row["已預(yù)約"] = 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 虛擬化數(shù)據(jù)// //DataTable datasource = new DataTable("tb");// //datasource.Columns.Add("類型");// //datasource.Columns.Add("已預(yù)約");// //datasource.Columns.Add("體檢中");// //datasource.Columns.Add("已打印");// //for (int i = 0; i < 3; i++)// //{// // var row = datasource.NewRow();// // row["類型"] = "分組" + i;// // row["已預(yù)約"] = 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 虛擬化數(shù)據(jù)// //DataTable datasource = new DataTable("tb");// //datasource.Columns.Add("類型");// //datasource.Columns.Add("已預(yù)約");// //datasource.Columns.Add("體檢中");// //datasource.Columns.Add("已打印");// //for (int i = 0; i < 1; i++)// //{// // var row = datasource.NewRow();// // row["類型"] = "分組" + i;// // row["已預(yù)約"] = 5 * (i + 1);// // row["體檢中"] = 3 * (i + 1);// // row["已打印"] = 9 * (i + 1);// // datasource.Rows.Add(row);// //}// 替換數(shù)據(jù)處理// //DataSet ds = new DataSet();// //ds.Tables.Add(datasource);// #endregion// InsertData_Replace(srcDoc, wordSeting, unitid);//} #endregionreturn srcDoc;}/// <summary>/// 添加分組列說明 liyouming /// </summary>/// <param name="chart"></param>/// <param name="seriesSize">分組數(shù)量</param>/// <param name="lableSize">列組數(shù)量</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>/// 設(shè)置顯示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圖形未設(shè)置數(shù)據(jù)源");}//獲取數(shù)據(jù)源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 分組統(tǒng)計(jì)圖,說明 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圖形未設(shè)置數(shù)據(jù)源");}//獲取數(shù)據(jù)源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 分組統(tǒng)計(jì)圖,說明 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圖形未設(shè)置數(shù)據(jù)源");}//獲取數(shù)據(jù)源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>/// 添加統(tǒng)計(jì)列表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未設(shè)置數(shù)據(jù)源");}//獲取數(shù)據(jù)源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數(shù)據(jù) /// </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;//獲取數(shù)據(jù)源
DocumentBuilder builder = new DocumentBuilder(doc);string htmlConetent = wordseting.WordHtml;//沒有數(shù)據(jù)源就直接插入html內(nèi)容if (datasource == null){}//有數(shù)據(jù)源把html當(dāng)作模版寫入 這里模版分為類型else{Regex regtag = new Regex(@"<temp class='TempIndex\d*'.*?>.*?</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("\r\n", "<br/>"));}}_sb1.Append(rowtemp);}htmlConetent = htmlConetent.Replace(temp, _sb1.ToString());}}}#endregionRegex regtable = new Regex(@"<table class='TableIndex\d*'.*?>.*?</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("\r\n", "<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未設(shè)置數(shù)據(jù)源");}//獲取數(shù)據(jù)源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){//這種設(shè)計(jì)數(shù)據(jù)源需用 Name Value 處理foreach (DataRow row in table.Rows){Regex reg1 = new Regex(@"{" + row["Name"] + "}");doc.Range.Replace(reg1, row["Value"] + "");}}}}return doc;}} Aspose.Words
?通過模版設(shè)計(jì)處理文檔,測(cè)試效果
?
轉(zhuǎn)載于:https://www.cnblogs.com/liyouming/p/8125882.html
總結(jié)
以上是生活随笔為你收集整理的Aspose.Words 自定义文档模版生成操作类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis基础(一)
- 下一篇: nodejs之日志管理