Aspose.Words 操作 Word 画 EChart 图

  使用 Aspose.Words 插件在 Word 画 EChart 图

  使用此插件可以画出丰富的 EChart 图,API 参考 https://reference.aspose.com/words/net/aspose.words.drawing.charts/charttype/

  首先需要在 vs 中引入插件

  

  代码中添加引用

using Aspose.Words;
using Aspose.Words.Drawing.Charts;
using Aspose.Words.Tables;

 

  1、插入文字内容和表格

    我们只需要获取模板,并且创建一个文档对象,将内容写入进去即可

    创建表格时,需要创建头,规定每个单元格长度,宽度,将对应的数据库字段对应上

 1 DataTable dt = new DataTable();
 2 
 3             //读取 Word 模板
 4             Document doc = new Document("C:\\TestProject\\WebApplication1\\WebApplication1\\Word\\AsposeWord.doc");
 5 
 6             //创建文档对象
 7             DocumentBuilder builder = new DocumentBuilder(doc);
 8 
 9             #region 插入文字信息
10             //Word 中对应书签的名称
11             builder.MoveToBookmark("文章标题");
12 
13             //写入内容
14             builder.Write("学会使用AsposeWord画EChart图");
15             #endregion
16 
17             #region 列表
18             builder.MoveToBookmark("学生信息列表");
19 
20             Aspose.Words.Tables.Table table3 = builder.StartTable();//开始画Table
21             string[] columnheadersWD = { "序号", "姓名", "学科", "分数", "性别", "年龄" };
22             string[] columnnamesWD = { "ID", "TNAME", "DNAME", "SAL", "TSEX", "AGE" };
23             double[] colwidthsWD = { 50, 100, 100, 50, 50, 50 };
24 
25             dt = DBHelper.ExecuteDataTable("SELECT top 5 * FROM [testdb].[dbo].[TEACHER]");
26 
27             InsertTable(builder, table3, columnheadersWD, columnnamesWD, colwidthsWD, dt);
28 
29             //第三列的 第三行,第四行 合并
30             MergeCells(table3.Rows[3].Cells[2], table3.Rows[4].Cells[2]);
31             #endregion
View Code

  这里我们将画表格的方法和合并单元格的方法封装好了

  1         /// <summary>
  2         /// 列表表格
  3         /// </summary>
  4         /// <param name="builder"></param>
  5         /// <param name="table"></param>
  6         /// <param name="columnheaders"></param>
  7         /// <param name="columnnames"></param>
  8         /// <param name="colwidths"></param>
  9         /// <param name="statisTable"></param>
 10         public static void InsertTable(DocumentBuilder builder, Aspose.Words.Tables.Table table, string[] columnheaders, string[] columnnames, double[] colwidths, DataTable statisTable)
 11         {
 12             var str = "";
 13 
 14             #region 画表头
 15             for (int i = 0; i < columnheaders.Length; i++)
 16             {
 17                 str = columnheaders[i];
 18                 builder.InsertCell();
 19                 //Table单元格边框线样式  
 20                 builder.CellFormat.Borders.LineStyle = LineStyle.Single;
 21                 //Table此单元格宽度  
 22                 builder.RowFormat.Height = 30;
 23                 builder.CellFormat.Width = colwidths[i];
 24                 //此单元格中内容垂直对齐方式  
 25                 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
 26                 builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
 27                 builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
 28                 //字体大小  
 29                 builder.Font.Size = 10;
 30                 //是否加粗  
 31                 builder.Bold = false;
 32                 //向此单元格中添加内容  
 33                 builder.Write(str);
 34             }
 35             builder.EndRow();
 36             #endregion
 37 
 38             #region 画数据
 39             for (int j = 0; j < statisTable.Rows.Count; j++)
 40             {
 41                 for (int i = 0; i < columnheaders.Length; i++)
 42                 {
 43                     try
 44                     {
 45                         str = statisTable.Rows[j][columnnames[i]].ToString();
 46                     }
 47                     catch (Exception e) { str = ""; }
 48                     builder.InsertCell();
 49                     //Table单元格边框线样式  
 50                     builder.CellFormat.Borders.LineStyle = LineStyle.Single;
 51                     //Table此单元格宽度  
 52                     builder.RowFormat.Height = 30;
 53                     builder.CellFormat.Width = colwidths[i];
 54 
 55                     //builder.CellFormat.Shading.ForegroundPatternColor = Color.Red;//设置单元格颜色
 56 
 57                     //此单元格中内容垂直对齐方式  
 58                     builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
 59                     builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
 60                     builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
 61                     //字体大小  
 62                     builder.Font.Size = 10;
 63                     //是否加粗  
 64                     builder.Bold = false;
 65                     //向此单元格中添加内容  
 66                     builder.Write(str);
 67                 }
 68                 builder.EndRow();
 69             }
 70             #endregion
 71 
 72             //Table行结束  
 73             builder.EndTable();
 74             table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);
 75             table.Alignment = Aspose.Words.Tables.TableAlignment.Center;
 76         }
 77 
 78         /// <summary>
 79         /// 合并单元格
 80         /// </summary>
 81         /// <param name="startCell"></param>
 82         /// <param name="endCell"></param>
 83         public static void MergeCells(Cell startCell, Cell endCell)
 84         {
 85             Aspose.Words.Tables.Table parentTable = startCell.ParentRow.ParentTable;
 86 
 87             // Find the row and cell indices for the start and end cell.
 88             Point startCellPos = new Point(startCell.ParentRow.IndexOf(startCell), parentTable.IndexOf(startCell.ParentRow));
 89             Point endCellPos = new Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow));
 90             // Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.
 91             Rectangle mergeRange = new Rectangle(Math.Min(startCellPos.X, endCellPos.X), Math.Min(startCellPos.Y, endCellPos.Y), Math.Abs(endCellPos.X - startCellPos.X) + 1,
 92             Math.Abs(endCellPos.Y - startCellPos.Y) + 1);
 93 
 94             foreach (Row row in parentTable.Rows)
 95             {
 96                 foreach (Cell cell in row.Cells)
 97                 {
 98                     Point currentPos = new Point(row.IndexOf(cell), parentTable.IndexOf(row));
 99 
100                     // Check if the current cell is inside our merge range then merge it.
101                     if (mergeRange.Contains(currentPos))
102                     {
103                         if (currentPos.X == mergeRange.X)
104                             cell.CellFormat.HorizontalMerge = CellMerge.First;
105                         else
106                             cell.CellFormat.HorizontalMerge = (CellMerge.Previous);
107 
108                         if (currentPos.Y == mergeRange.Y)
109                             cell.CellFormat.VerticalMerge = (CellMerge.First);
110                         else
111                             cell.CellFormat.VerticalMerge = (CellMerge.Previous);
112                     }
113                 }
114             }
115         }
View Code

 

  2、单双曲线图,饼图,柱状图

    曲线图需要用到 InsertChart 方法指定图表类型 Line,这三种图区别不大方法一样,只需要指定图表类型

    ChartSeriesCollection seriesCollection = chart.Series; 提供了向图表插入数据的操作,有点类似 List 如果你只有一条曲线(柱状图),写一个 Add 就行,如果是多条曲线(柱状图),则添加多个 Add 数据即可展示多条曲线(柱状图)

 1 #region 曲线
 2             builder.MoveToBookmark("双曲线");
 3             var shape = builder.InsertChart(ChartType.Line, 430, 210);//插入线形图
 4             Chart chart = shape.Chart;
 5             ChartSeriesCollection seriesCollection = chart.Series;
 6             seriesCollection.Clear();//清除默认 
 7             chart.Title.Text = "双曲线";
 8             chart.AxisX.TickLabelPosition = AxisTickLabelPosition.Low;
 9 
10             dt = DBHelper.ExecuteDataTable("select top 5 TNAME,sal,sal+100 as SAL1 from TEACHER");
11 
12             var categories = new string[dt.Rows.Count];
13             var values = new double[dt.Rows.Count];
14             var values1 = new double[dt.Rows.Count];
15 
16             for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
17             {
18                 categories[rowIndex] = dt.Rows[rowIndex][0].ToString();
19                 values[rowIndex] = Convert.ToDouble(dt.Rows[rowIndex][1]);
20                 values1[rowIndex] = Convert.ToDouble(dt.Rows[rowIndex][2]);
21             }
22 
23             chart.Legend.Position = LegendPosition.Top;
24 
25             seriesCollection.Add("线条一", categories, values);//添加数据
26             seriesCollection.Add("线条二", categories, values1);//添加数据
27             #endregion
28 
29             #region 饼状图
30             dt = DBHelper.ExecuteDataTable("select top 1 sal,sal+100 as SAL1,sal+200 as SAL2 from TEACHER");
31 
32             List<CountModel> list1 = new List<CountModel>();
33             for (int i = 0; i < dt.Rows.Count; i++)
34             {
35                 list1.Add(new CountModel { mark = "", num = Convert.ToDouble(dt.Rows[i][0]) });
36                 list1.Add(new CountModel { mark = "", num = Convert.ToDouble(dt.Rows[i][1]) });
37                 list1.Add(new CountModel { mark = "", num = Convert.ToDouble(dt.Rows[i][2]) });
38             }
39 
40             builder.MoveToBookmark("饼状图");
41             var shape1 = builder.InsertChart(ChartType.Pie, 430, 210);//插入线形图
42             Chart chart1 = shape1.Chart;
43             ChartSeriesCollection seriesCollection1 = chart1.Series;
44             seriesCollection1.Clear();//清除默认 
45             chart1.Title.Text = "饼状图";
46 
47             var categories2 = new string[list1.Count];
48             var values2 = new double[list1.Count];
49 
50             for (int rowIndex = 0; rowIndex < list1.Count; rowIndex++)
51             {
52                 categories2[rowIndex] = list1[rowIndex].mark.ToString();
53                 values2[rowIndex] = Convert.ToDouble(list1[rowIndex].num);
54             }
55 
56             chart1.Legend.Position = LegendPosition.Top;
57 
58             seriesCollection1.Add("饼状图", categories2, values2);//添加数据
59             #endregion
60 
61             #region 柱状图
62             dt = DBHelper.ExecuteDataTable("select top 5 tname,sal,sal+100 as SAL1,sal+200 as SAL2 from TEACHER");
63 
64             builder.MoveToBookmark("柱状图");
65             var shape2 = builder.InsertChart(ChartType.Column, 430, 210);//插入线形图
66             Chart chart2 = shape2.Chart;
67             ChartSeriesCollection seriesCollection3 = chart2.Series;
68             seriesCollection3.Clear();//清除默认 
69             chart2.Title.Text = "柱状图";
70             chart2.AxisX.TickLabelPosition = AxisTickLabelPosition.Low;
71 
72             var categories3 = new string[dt.Rows.Count];
73             var values11 = new double[dt.Rows.Count];
74             var values22 = new double[dt.Rows.Count];
75             var values3 = new double[dt.Rows.Count];
76 
77             for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
78             {
79                 categories3[rowIndex] = dt.Rows[rowIndex][0].ToString();
80                 values11[rowIndex] = Convert.ToDouble(dt.Rows[rowIndex][1]);
81                 values22[rowIndex] = Convert.ToDouble(dt.Rows[rowIndex][2]);
82                 values3[rowIndex] = Convert.ToDouble(dt.Rows[rowIndex][3]);
83             }
84 
85             chart2.Legend.Position = LegendPosition.Top;
86 
87             seriesCollection3.Add("", categories3, values11);//添加数据
88             seriesCollection3.Add("", categories3, values22);//添加数据
89             seriesCollection3.Add("", categories3, values3);//添加数据
90             #endregion
View Code

 

  3、散点图

    散点图跟其他图略有区别,散点图是 XY 的坐标点形式处理数据

 1 #region 散点图
 2             var result = new List<SD>();
 3             result.Add(new SD() { wd = 15, wy = 16 });
 4             result.Add(new SD() { wd = 14, wy = 23 });
 5             result.Add(new SD() { wd = 34, wy = 23 });
 6             result.Add(new SD() { wd = 12, wy = 23 });
 7             result.Add(new SD() { wd = 34, wy = 45 });
 8             result.Add(new SD() { wd = 32, wy = 23 });
 9             result.Add(new SD() { wd = 45, wy = 56 });
10             result.Add(new SD() { wd = 34, wy = 55 });
11 
12             builder.MoveToBookmark("散点图");
13             var shape3 = builder.InsertChart(ChartType.Scatter, 430, 210);//插入线形图
14             Chart chart3 = shape3.Chart;
15             ChartSeriesCollection seriesCollection4 = chart3.Series;
16             seriesCollection4.Clear();//清除默认 
17             chart3.Title.Text = "散点图";
18             chart3.AxisX.TickLabelPosition = AxisTickLabelPosition.Low;
19 
20             var categories4 = new double[result.Count];
21             var values4 = new double[result.Count];
22 
23             for (int i = 0; i < result.Count; i++)
24             {
25                 categories4[i] = Convert.ToDouble(result[i].wd);
26                 values4[i] = Convert.ToDouble(result[i].wy);
27             }
28 
29             chart3.Legend.Position = LegendPosition.Top;
30             seriesCollection4.Add("散点图", categories4, values4);//添加数据
31             #endregion
View Code

 

  最后将内容输出到指定的新文档中

1 string cpath = "C:\\TestProject\\测试文档存放\\文档" + DateTime.Now.ToString("ddhhmmss") + ".doc";
2 doc.Save(cpath);
3 doc.Save(cpath.Replace(".doc", ".pdf"), SaveFormat.Pdf);  //同时转成 PDF 生成一份

  这里只是简单的操作显示图表,如果需要具体详细的细节操作,参考官方提供的API文档。

 

  效果图

 

posted @ 2022-10-21 17:03  object0812  阅读(1682)  评论(0编辑  收藏  举报