码迷,mamicode.com
首页 > 其他好文 > 详细

利用openxml在Excel中插入图表

时间:2018-09-07 11:12:43      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:value   图形   ping   auto   标题   line   min   reference   span   

  1 using System.Collections.Generic;
  2 using System.Linq;
  3 using DOD = DocumentFormat.OpenXml.Drawing;
  4 using DODC = DocumentFormat.OpenXml.Drawing.Charts;
  5 using DODS = DocumentFormat.OpenXml.Drawing.Spreadsheet;
  6 using DOS = DocumentFormat.OpenXml.Spreadsheet;
  7 using DOX = DocumentFormat.OpenXml;
  8 using pkg = DocumentFormat.OpenXml.Packaging;
  9 
 10 namespace  InsertChartTest
 11 {
 12     class Program
 13     {
 14         const string fileName = @"C:\Users\Administrator\source\repos\OpenXMLStudy\OpenXMLStudy\Sum100.xlsx";
 15 
 16         static void Main(string[] args)
 17         {
 18             string worksheetName = "Joe";
 19             string title = "New Chart";
 20             Dictionary<string, int> data = new Dictionary<string, int>();
 21             data.Add("abc", 1);
 22             data.Add("dsa", 2);
 23             InsertChartInSpreadsheet(fileName, worksheetName, title, data);
 24 
 25         }
 26 
 27         private static void InsertChartInSpreadsheet(string docName, string worksheetName, string title,
 28     Dictionary<string, int> data)
 29         {
 30             using (pkg.SpreadsheetDocument document = pkg.SpreadsheetDocument.Open(docName, true))
 31             {
 32                 IEnumerable<DOS.Sheet> sheets = document.WorkbookPart.Workbook.Descendants<DOS.Sheet>();
 33 
 34                 if (sheets == null || sheets.Count() <= 0)
 35                     return;
 36 
 37                 pkg.WorksheetPart worksheetPart = (pkg.WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
 38 
 39                 System.Diagnostics.Debug.WriteLine("SheetID:{0}", sheets.First().Id);
 40 
 41                 // DOS.Worksheet worksheet = worksheetPart.Worksheet;
 42                 pkg.DrawingsPart drawingsPart = worksheetPart.AddNewPart<pkg.DrawingsPart>();
 43 
 44                 worksheetPart.Worksheet.Append(new DOS.Drawing()
 45                 {
 46                     Id = worksheetPart.GetIdOfPart(drawingsPart)
 47                 });
 48                 worksheetPart.Worksheet.Save();
 49 
 50                 pkg.ChartPart chartPart = drawingsPart.AddNewPart<pkg.ChartPart>();
 51 
 52                 //图表实例
 53                 chartPart.ChartSpace = new DODC.ChartSpace();
 54 
 55                 chartPart.ChartSpace.Append(
 56                     new DODC.EditingLanguage()
 57                     {
 58                         Val = new DOX.StringValue("en-US")
 59                     });
 60 
 61                 //图表最外层
 62                 DODC.Chart chart = chartPart.ChartSpace.AppendChild<DODC.Chart>(new DODC.Chart());
 63 
 64                 //图形区
 65                 DODC.PlotArea plotArea = chart.AppendChild<DODC.PlotArea>(new DODC.PlotArea());
 66 
 67                 //布局
 68                 DODC.Layout layout = plotArea.AppendChild<DODC.Layout>(new DODC.Layout());
 69 
 70                 //柱形图
 71                 DODC.BarChart barChart = plotArea
 72                     .AppendChild<DODC.BarChart>(
 73                     new DODC.BarChart(
 74                         new DODC.BarDirection()
 75                         {
 76                             Val = new DOX.EnumValue<DODC.BarDirectionValues>(DODC.BarDirectionValues.Column)
 77                         },
 78                         new DODC.BarGrouping()
 79                         {
 80                             Val = new DOX.EnumValue<DODC.BarGroupingValues>(DODC.BarGroupingValues.Clustered)
 81                         }));
 82 
 83                 uint i = 0;
 84 
 85                 foreach (string key in data.Keys)
 86                 {
 87                     //柱形图序列
 88                     DODC.BarChartSeries barChartSeries = barChart
 89                         .AppendChild<DODC.BarChartSeries>(
 90                         new DODC.BarChartSeries(//柱形图序列
 91                             new DODC.Index()
 92                             {
 93                                 Val = new DOX.UInt32Value(i)
 94                             },
 95                             new DODC.Order()
 96                             {
 97                                 Val = new DOX.UInt32Value(i)
 98                             },
 99                             new DODC.SeriesText( //系列文本
100                                 new DODC.NumericValue()
101                                 {
102                                     Text = key
103                                 })
104                             ));
105 
106                     //字符串常值
107                     DODC.StringLiteral strLit = barChartSeries
108                         .AppendChild<DODC.CategoryAxisData>(
109                         new DODC.CategoryAxisData())
110                         .AppendChild<DODC.StringLiteral>(
111                         new DODC.StringLiteral());
112 
113                     strLit.Append(new DODC.PointCount()
114                     {
115                         Val = new DOX.UInt32Value(1U)
116                     });
117 
118                     strLit.AppendChild<DODC.StringPoint>(new DODC.StringPoint()
119                     {
120                         Index = new DOX.UInt32Value(0U)
121                     })
122                     .Append(new DODC.NumericValue(key)); //原为title
123 
124                     //值常值
125                     DODC.NumberLiteral numLit = barChartSeries
126                         .AppendChild<DODC.Values>(new DODC.Values()
127                         ).AppendChild<DODC.NumberLiteral>(new DODC.NumberLiteral()
128                         );
129 
130                     numLit.Append(new DODC.FormatCode("General"));
131 
132                     numLit.Append(new DODC.PointCount()
133                     {
134                         Val = new DOX.UInt32Value(1U)
135                     });
136 
137                     numLit.AppendChild<DODC.NumericPoint>(new DODC.NumericPoint()
138                     {
139                         Index = new DOX.UInt32Value(0u)
140                     }).Append(new DODC.NumericValue(data[key].ToString()));
141 
142                     i++;
143                 }
144 
145                 barChart.Append(new DODC.AxisId()
146                 {
147                     Val = new DOX.UInt32Value(48650112u)
148                 });
149 
150                 barChart.Append(new DODC.AxisId()
151                 {
152                     Val = new DOX.UInt32Value(48672768u)
153                 });
154 
155                 //分类坐标值
156                 DODC.CategoryAxis catAx = plotArea.AppendChild<DODC.CategoryAxis>(
157                     new DODC.CategoryAxis(
158                         new DODC.AxisId()
159                         {
160                             Val = new DOX.UInt32Value(48650112u)
161                         },
162                         new DODC.Scaling(new DODC.Orientation()
163                         {
164                             Val = new DOX.EnumValue<DODC.OrientationValues>(DODC.OrientationValues.MinMax)
165                         }),
166                         new DODC.AxisPosition()//坐标值位置
167                         {
168                             Val = new DOX.EnumValue<DODC.AxisPositionValues>(DODC.AxisPositionValues.Bottom)
169                         },
170                         new DODC.TickLabelPosition()//标签位置
171                         {
172                             Val = new DOX.EnumValue<DODC.TickLabelPositionValues>(DODC.TickLabelPositionValues.NextTo)
173                         },
174                         new DODC.CrossingAxis()
175                         {
176                             Val = new DOX.UInt32Value(48672768U)
177                         },
178                         new DODC.Crosses()
179                         {
180                             Val = new DOX.EnumValue<DODC.CrossesValues>(DODC.CrossesValues.AutoZero)
181                         },
182                         new DODC.AutoLabeled()
183                         {
184                             Val = new DOX.BooleanValue(true)
185                         },
186                         new DODC.LabelAlignment()
187                         {
188                             Val = new DOX.EnumValue<DODC.LabelAlignmentValues>(DODC.LabelAlignmentValues.Center)
189                         },
190                         new DODC.LabelOffset()
191                         {
192                             Val = new DOX.UInt16Value((ushort)100)
193                         }
194                         ));
195 
196                 //值坐标值
197                 DODC.ValueAxis valAx = plotArea.AppendChild<DODC.ValueAxis>(
198                     new DODC.ValueAxis(
199                         new DODC.AxisId()
200                         {
201                             Val = new DOX.UInt32Value(48672768u)
202                         }, 
203                         new DODC.Scaling(
204                             new DODC.Orientation()
205                             {
206                                 Val = new DOX.EnumValue<DODC.OrientationValues>(DODC.OrientationValues.MinMax)
207                             }), 
208                         new DODC.AxisPosition()
209                         {
210                             Val = new DOX.EnumValue<DODC.AxisPositionValues>(DODC.AxisPositionValues.Left)
211                         }, 
212                         new DODC.MajorGridlines(), 
213                         new DODC.NumberingFormat()
214                         {
215                             FormatCode = new DOX.StringValue("General"),
216                             SourceLinked = new DOX.BooleanValue(true)
217                         }, 
218                         new DODC.TickLabelPosition()
219                         {
220                             Val = new DOX.EnumValue<DODC.TickLabelPositionValues>(DODC.TickLabelPositionValues.NextTo)
221                         },
222                         new DODC.CrossingAxis()
223                         {
224                             Val = new DOX.UInt32Value(48650112U)
225                         }, 
226                         new DODC.Crosses()
227                         {
228                             Val = new DOX.EnumValue<DODC.CrossesValues>(DODC.CrossesValues.AutoZero)
229                         }, 
230                         new DODC.CrossBetween()
231                         {
232                             Val = new DOX.EnumValue<DODC.CrossBetweenValues>(DODC.CrossBetweenValues.Between)
233                         }));
234 
235 
236                 //图例
237                 DODC.Legend legend = chart.AppendChild<DODC.Legend>(
238                     new DODC.Legend(
239                         new DODC.LegendPosition()
240                         {
241                             Val = new DOX.EnumValue<DODC.LegendPositionValues>(DODC.LegendPositionValues.Right) //图例位置
242                         }));
243 
244                 //图可见
245                 chart.Append(new DODC.PlotVisibleOnly()
246                 {
247                     Val = new DOX.BooleanValue(true)
248                 });
249 
250                 chartPart.ChartSpace.Save();
251 
252                 drawingsPart.WorksheetDrawing = new DODS.WorksheetDrawing();
253 
254                 //图例和图形区域大小
255                 DODS.TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<DODS.TwoCellAnchor>(new DODS.TwoCellAnchor());
256 
257                 //图形区域大小
258                 twoCellAnchor.Append(new DODS.FromMarker(new DODS.ColumnId("9"),
259                 new DODS.ColumnOffset("581025"),
260                 new DODS.RowId("17"),
261                 new DODS.RowOffset("114300")));
262 
263                 //图例区域大小
264                 twoCellAnchor.Append(new DODS.ToMarker(new DODS.ColumnId("17"),
265                     new DODS.ColumnOffset("276225"),
266                     new DODS.RowId("32"),
267                     new DODS.RowOffset("0")));
268 
269 
270                 //添加图形和图例到区域中
271                 //图形框架
272                 DODS.GraphicFrame graphicFrame =
273                 twoCellAnchor.AppendChild<DODS.GraphicFrame>(new DODS.GraphicFrame());
274                 graphicFrame.Macro = "";
275 
276                 //图表标题
277                 graphicFrame.Append(
278                     new DODS.NonVisualGraphicFrameProperties(
279                         new DODS.NonVisualDrawingProperties()
280                         {
281                             Id = new DOX.UInt32Value(2u),
282                             Name = "Chart 1"
283                         },
284                         new DODS.NonVisualGraphicFrameDrawingProperties()
285                         ));
286 
287                 //区域坐标
288                 graphicFrame.Append(
289                     new DODS.Transform(
290                         new DOD.Offset()
291                         {
292                             X = 0L,
293                             Y = 0L
294                         },
295                         new DOD.Extents()
296                         {
297                             Cx = 0L,
298                             Cy = 0L
299                         }
300                         ));
301 
302                 //把图形添加到区域中
303                 graphicFrame.Append(
304                     new DOD.Graphic(
305                         new DOD.GraphicData(
306                             new DODC.ChartReference()
307                             {
308                                 Id = drawingsPart.GetIdOfPart(chartPart)//指定图形ID
309                             })
310                 { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }
311                         ));
312 
313                 twoCellAnchor.Append(new DODS.ClientData());
314 
315                 drawingsPart.WorksheetDrawing.Save();
316 
317             }
318         }
319     }
320 }

运行上面代码得到图表如图:

技术分享图片

注意:上面代码不支持重复运行

利用openxml在Excel中插入图表

标签:value   图形   ping   auto   标题   line   min   reference   span   

原文地址:https://www.cnblogs.com/kingline/p/9602561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!