-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathChartUpdater.cs
650 lines (600 loc) · 28.9 KB
/
ChartUpdater.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
namespace OpenXmlPowerTools
{
public enum ChartDataType
{
Number,
String,
DateTime,
}
// Format Codes
// 0 - general
// 1 - 0
// 2 - 0.00
// 3 - #,##0
// 4 - #,##0.00
// 9 - 0%
// 10 - 0.00%
// 11 - 0.00E+00
// 12 - # ?/?
// 13 - # ??/??
// 14 - mm-dd-yy
// 15 - d-mmm-yy
// 16 - d-mmm
// 17 - mmm-yy
// 18 - h:mm AM/PM
// 19 - h:mm:ss AM/PM
// 20 - h:mm
// 21 - h:mm:ss
// 22 - m/d/yy h:mm
// 37 - #,##0 ;(#,##0)
// 38 - #,##0 ;[Red](#,##0)
// 39 - #,##0.00;(#,##0.00)
// 40 - #,##0.00;[Red](#,##0.00)
// 45 - mm:ss
// 46 - [h]:mm:ss
// 47 - mmss.0
// 48 - ##0.0E+0
// 49 - @
public class ChartData
{
public string[] SeriesNames;
public ChartDataType CategoryDataType;
public int CategoryFormatCode;
public string[] CategoryNames;
public double[][] Values;
/// <summary>
/// 组合图表中,第二个图表的序列索引.
/// 这些序列数据会被复制到第二个图表的序列中.
/// </summary>
public int[] SecondChartSeriesIndex;
public XName SecondChartType;
}
public class ChartUpdater
{
public static bool UpdateChart(WordprocessingDocument wDoc, string contentControlTag, ChartData chartData)
{
var mainDocumentPart = wDoc.MainDocumentPart;
var mdXDoc = mainDocumentPart.GetXDocument();
var cc = mdXDoc.Descendants(W.sdt)
.FirstOrDefault(sdt => (string)sdt.Elements(W.sdtPr).Elements(W.tag).Attributes(W.val).FirstOrDefault() == contentControlTag);
if (cc != null)
{
var chartRid = (string)cc.Descendants(C.chart).Attributes(R.id).FirstOrDefault();
if (chartRid != null)
{
ChartPart chartPart = (ChartPart)mainDocumentPart.GetPartById(chartRid);
UpdateChart(chartPart, chartData);
var newContent = cc.Elements(W.sdtContent).Elements().Select(e => new XElement(e));
cc.ReplaceWith(newContent);
mainDocumentPart.PutXDocument();
return true;
}
}
return false;
}
public static void UpdateChart(ChartPart chartPart, ChartData chartData)
{
if (chartData.Values.Length != chartData.SeriesNames.Length)
throw new ArgumentException("Invalid chart data");
foreach (var ser in chartData.Values)
{
if (ser.Length != chartData.CategoryNames.Length)
throw new ArgumentException("Invalid chart data");
}
UpdateSeries(chartPart, chartData);
MoveSecondChartSeries(chartPart, chartData);
}
/// <summary>
/// 移动第二图表的序列数据.
/// </summary>
/// <param name="chartPart">图表部件.</param>
/// <param name="chartData">图表数据.</param>
private static void MoveSecondChartSeries(ChartPart chartPart, ChartData chartData)
{
if (chartData.SecondChartType == null)
{
return;
}
if (chartData.SecondChartSeriesIndex != null && chartData.SecondChartSeriesIndex.Length == 0)
{
return;
}
XDocument cpXDoc = chartPart.GetXDocument();
XElement root = cpXDoc.Root;
// 根据配置得到序列
var series = chartData.SecondChartSeriesIndex.Select(x =>
root.Descendants(C.ser).ElementAt(x)
).ToList();
var firstParent = series.First().Parent;
var chart = root.Descendants(chartData.SecondChartType).FirstOrDefault();
var firstSeries = chart.Descendants(C.ser).FirstOrDefault();
firstSeries.Parent.Elements(C.ser).Skip(1).Remove();
firstSeries.ReplaceWith(series);
// 删除旧series
series.Remove();
chartPart.PutXDocument();
}
private static Dictionary<int, string> FormatCodes = new Dictionary<int, string>()
{
{ 0, "general" },
{ 1, "0" },
{ 2, "0.00" },
{ 3, "#,##0" },
{ 4, "#,##0.00" },
{ 9, "0%" },
{ 10, "0.00%" },
{ 11, "0.00E+00" },
{ 12, "# ?/?" },
{ 13, "# ??/??" },
{ 14, "mm-dd-yy" },
{ 15, "d-mmm-yy" },
{ 16, "d-mmm" },
{ 17, "mmm-yy" },
{ 18, "h:mm AM/PM" },
{ 19, "h:mm:ss AM/PM" },
{ 20, "h:mm" },
{ 21, "h:mm:ss" },
{ 22, "m/d/yy h:mm" },
{ 37, "#,##0 ;(#,##0)" },
{ 38, "#,##0 ;[Red](#,##0)" },
{ 39, "#,##0.00;(#,##0.00)" },
{ 40, "#,##0.00;[Red](#,##0.00)" },
{ 45, "mm:ss" },
{ 46, "[h]:mm:ss" },
{ 47, "mmss.0" },
{ 48, "##0.0E+0" },
{ 49, "@" },
};
private static void UpdateSeries(ChartPart chartPart, ChartData chartData)
{
UpdateEmbeddedWorkbook(chartPart, chartData);
XDocument cpXDoc = chartPart.GetXDocument();
XElement root = cpXDoc.Root;
var firstSeries = root.Descendants(C.ser).FirstOrDefault();
var numRef = firstSeries.Elements(C.val).Elements(C.numRef).FirstOrDefault();
string sheetName = null;
var f = (string)firstSeries.Descendants(C.f).FirstOrDefault();
if (f != null)
sheetName = f.Split('!')[0];
// remove all but first series
XName chartType = firstSeries.Parent.Name;
firstSeries.Parent.Elements(C.ser).Skip(1).Remove();
var newSetOfSeries = chartData.SeriesNames
.Select((string sn, int si) =>
{
XElement cat = null;
var oldCat = firstSeries.Elements(C.cat).FirstOrDefault();
if (oldCat == null)
throw new OpenXmlPowerToolsException("Invalid chart markup");
var catHasFormula = oldCat.Descendants(C.f).Any();
if (catHasFormula)
{
XElement newFormula = null;
if (sheetName != null)
newFormula = new XElement(C.f, string.Format("{0}!$A$2:$A${1}", sheetName, chartData.CategoryNames.Length + 1));
if (chartData.CategoryDataType == ChartDataType.String)
{
cat = new XElement(C.cat,
new XElement(C.strRef,
newFormula,
new XElement(C.strCache,
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.CategoryNames[ci]));
return newPt;
}))));
}
else
{
cat = new XElement(C.cat,
new XElement(C.numRef,
newFormula,
new XElement(C.numCache,
new XElement(C.formatCode, FormatCodes[chartData.CategoryFormatCode]),
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.CategoryNames[ci]));
return newPt;
}))));
}
}
else
{
if (chartData.CategoryDataType == ChartDataType.String)
{
cat = new XElement(C.cat,
new XElement(C.strLit,
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.CategoryNames[ci]));
return newPt;
})));
}
else
{
cat = new XElement(C.cat,
new XElement(C.numLit,
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.CategoryNames[ci]));
return newPt;
})));
}
}
XElement newCval = null;
if (sheetName == null)
{
newCval = new XElement(C.val,
new XElement(C.numLit,
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.Values[si][ci]));
return newPt;
})));
}
else
{
newCval = new XElement(C.val,
new XElement(C.numRef,
sheetName != null ?
new XElement(C.f, string.Format("{0}!${2}$2:${2}${1}", sheetName, chartData.CategoryNames.Length + 1, SpreadsheetMLUtil.IntToColumnId(si + 1))) : null,
new XElement(C.numCache,
sheetName != null ? numRef.Descendants(C.formatCode) : null,
new XElement(C.ptCount, new XAttribute("val", chartData.CategoryNames.Length)),
chartData.CategoryNames.Select((string cn, int ci) =>
{
var newPt = new XElement(C.pt,
new XAttribute("idx", ci),
new XElement(C.v, chartData.Values[si][ci]));
return newPt;
}))));
}
var serHasFormula = firstSeries.Descendants(C.f).Any();
XElement tx = null;
if (serHasFormula)
{
XElement newFormula = null;
if (sheetName != null)
newFormula = new XElement(C.f, string.Format("{0}!${1}$1", sheetName, SpreadsheetMLUtil.IntToColumnId(si + 1)));
tx = new XElement(C.tx,
new XElement(C.strRef,
newFormula,
new XElement(C.strCache,
new XElement(C.ptCount, new XAttribute("val", 1)),
new XElement(C.pt,
new XAttribute("idx", 0),
new XElement(C.v, chartData.SeriesNames[si])))));
}
else
{
tx = new XElement(C.tx,
new XElement(C.v, chartData.SeriesNames[si]));
}
XElement newSer = null;
if (chartType == C.area3DChart || chartType == C.areaChart)
{
newSer = new XElement(C.ser,
// common
new XElement(C.idx, new XAttribute("val", si)),
new XElement(C.order, new XAttribute("val", si)),
tx,
firstSeries.Elements(C.spPr),
// CT_AreaSer
firstSeries.Elements(C.pictureOptions),
firstSeries.Elements(C.dPt),
firstSeries.Elements(C.dLbls),
firstSeries.Elements(C.trendline),
firstSeries.Elements(C.errBars),
cat,
newCval,
firstSeries.Elements(C.extLst));
}
else if (chartType == C.bar3DChart || chartType == C.barChart)
{
newSer = new XElement(C.ser,
// common
new XElement(C.idx, new XAttribute("val", si)),
new XElement(C.order, new XAttribute("val", si)),
tx,
firstSeries.Elements(C.spPr),
// CT_BarSer
firstSeries.Elements(C.invertIfNegative),
firstSeries.Elements(C.pictureOptions),
firstSeries.Elements(C.dPt),
firstSeries.Elements(C.dLbls),
firstSeries.Elements(C.trendline),
firstSeries.Elements(C.errBars),
cat,
newCval,
firstSeries.Elements(C.shape),
firstSeries.Elements(C.extLst));
}
else if (chartType == C.line3DChart || chartType == C.lineChart || chartType == C.stockChart)
{
newSer = new XElement(C.ser,
// common
new XElement(C.idx, new XAttribute("val", si)),
new XElement(C.order, new XAttribute("val", si)),
tx,
firstSeries.Elements(C.spPr),
// CT_LineSer
firstSeries.Elements(C.marker),
firstSeries.Elements(C.dPt),
firstSeries.Elements(C.dLbls),
firstSeries.Elements(C.trendline),
firstSeries.Elements(C.errBars),
cat,
newCval,
firstSeries.Elements(C.smooth),
firstSeries.Elements(C.extLst));
}
else if (chartType == C.doughnutChart || chartType == C.ofPieChart || chartType == C.pie3DChart || chartType == C.pieChart)
{
newSer = new XElement(C.ser,
// common
new XElement(C.idx, new XAttribute("val", si)),
new XElement(C.order, new XAttribute("val", si)),
tx,
firstSeries.Elements(C.spPr),
// CT_PieSer
firstSeries.Elements(C.explosion),
firstSeries.Elements(C.dPt),
firstSeries.Elements(C.dLbls),
cat,
newCval,
firstSeries.Elements(C.extLst));
}
else if (chartType == C.surface3DChart || chartType == C.surfaceChart)
{
newSer = new XElement(C.ser,
// common
new XElement(C.idx, new XAttribute("val", si)),
new XElement(C.order, new XAttribute("val", si)),
tx,
firstSeries.Elements(C.spPr),
// CT_SurfaceSer
cat,
newCval,
firstSeries.Elements(C.extLst));
}
if (newSer == null)
throw new OpenXmlPowerToolsException("Unsupported chart type");
int accentNumber = (si % 6) + 1;
newSer = (XElement)UpdateAccentTransform(newSer, accentNumber);
return newSer;
});
firstSeries.ReplaceWith(newSetOfSeries);
chartPart.PutXDocument();
}
private static void UpdateEmbeddedWorkbook(ChartPart chartPart, ChartData chartData)
{
XDocument cpXDoc = chartPart.GetXDocument();
XElement root = cpXDoc.Root;
var firstSeries = root.Descendants(C.ser).FirstOrDefault();
if (firstSeries == null)
return;
var firstFormula = (string)firstSeries.Descendants(C.f).FirstOrDefault();
if (firstFormula == null)
return;
var sheet = firstFormula.Split('!')[0];
var embeddedSpreadsheetRid = (string)root.Descendants(C.externalData).Attributes(R.id).FirstOrDefault();
if (embeddedSpreadsheetRid == null)
return;
var embeddedSpreadsheet = chartPart.GetPartById(embeddedSpreadsheetRid);
if (embeddedSpreadsheet != null)
{
using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(embeddedSpreadsheet.GetStream(), true))
{
var workbookPart = sDoc.WorkbookPart;
var wbRoot = workbookPart.GetXDocument().Root;
var sheetRid = (string)wbRoot
.Elements(S.sheets)
.Elements(S.sheet)
.Where(s => (string)s.Attribute("name") == sheet)
.Attributes(R.id)
.FirstOrDefault();
if (sheetRid != null)
{
var sheetPart = workbookPart.GetPartById(sheetRid);
var xdSheet = sheetPart.GetXDocument();
var sheetData = xdSheet.Descendants(S.sheetData).FirstOrDefault();
var stylePart = workbookPart.WorkbookStylesPart;
var xdStyle = stylePart.GetXDocument();
int categoryStyleId = 0;
if (chartData.CategoryFormatCode != 0)
categoryStyleId = AddDxfToDxfs(xdSheet, xdStyle, chartData.CategoryFormatCode);
stylePart.PutXDocument();
var firstRow = new XElement(S.row,
new XAttribute("r", "1"),
new XAttribute("spans", string.Format("1:{0}", chartData.SeriesNames.Length + 1)),
new[] { new XElement(S.c,
new XAttribute("r", "A1"),
new XAttribute("t", "str"),
new XElement(S.v,
new XAttribute(XNamespace.Xml + "space", "preserve"),
" "))}
.Concat(
chartData.SeriesNames
.Select((sn, i) => new XElement(S.c,
new XAttribute("r", RowColToString(0, i + 1)),
new XAttribute("t", "str"),
new XElement(S.v, sn)))));
var otherRows = chartData
.CategoryNames
.Select((cn, r) =>
{
var row = new XElement(S.row,
new XAttribute("r", r + 2),
new XAttribute("spans", string.Format("1:{0}", chartData.SeriesNames.Length + 1)),
new[] {
new XElement(S.c,
new XAttribute("r", RowColToString(r + 1, 0)),
categoryStyleId != 0 ? new XAttribute("s", categoryStyleId) : null,
chartData.CategoryDataType == ChartDataType.String ? new XAttribute("t", "str") : null,
new XElement(S.v, cn))
}.Concat(
Enumerable.Range(0, chartData.Values.Length)
.Select((c, ci) =>
{
var cell = new XElement(S.c,
new XAttribute("r", RowColToString(r + 1, ci + 1)),
new XElement(S.v, chartData.Values[ci][r]));
return cell;
})));
return row;
});
var allRows = new[] {
firstRow
}.Concat(otherRows);
var newSheetData = new XElement(S.sheetData,
allRows);
sheetData.ReplaceWith(newSheetData);
sheetPart.PutXDocument();
var tablePartRid = (string)xdSheet
.Root
.Elements(S.tableParts)
.Elements(S.tablePart)
.Attributes(R.id)
.FirstOrDefault();
if (tablePartRid != null)
{
var partTable = sheetPart.GetPartById(tablePartRid);
var xdTablePart = partTable.GetXDocument();
var xaRef = xdTablePart.Root.Attribute("ref");
xaRef.Value = string.Format("A1:{0}", RowColToString(chartData.CategoryNames.Length - 1, chartData.SeriesNames.Length));
var xeNewTableColumns = new XElement(S.tableColumns,
new XAttribute("count", chartData.SeriesNames.Count() + 1),
new[] {
new XElement(S.tableColumn,
new XAttribute("id", 1),
new XAttribute("name", " "))
}.Concat(
chartData.SeriesNames.Select((cn, ci) =>
new XElement(S.tableColumn,
new XAttribute("id", ci + 2),
new XAttribute("name", cn)))));
var xeExistingTableColumns = xdTablePart.Root.Element(S.tableColumns);
if (xeExistingTableColumns != null)
xeExistingTableColumns.ReplaceWith(xeNewTableColumns);
partTable.PutXDocument();
}
}
}
}
}
private static int AddDxfToDxfs(XDocument xdSheet, XDocument xdStyle, int formatCodeToAdd)
{
// add xf to cellXfs
var cellXfs = xdStyle
.Root
.Element(S.cellXfs);
if (cellXfs == null)
{
var cellStyleXfs = xdStyle
.Root
.Element(S.cellStyleXfs);
if (cellStyleXfs != null)
{
cellStyleXfs.AddAfterSelf(
new XElement(S.cellXfs,
new XAttribute("count", 0)));
cellXfs = xdSheet
.Root
.Element(S.cellXfs);
}
}
if (cellXfs == null)
{
var borders = xdStyle
.Root
.Element(S.borders);
if (borders != null)
{
borders.AddAfterSelf(
new XElement(S.cellXfs,
new XAttribute("count", 0)));
cellXfs = xdSheet
.Root
.Element(S.cellXfs);
}
}
if (cellXfs == null)
throw new OpenXmlPowerToolsException("Internal error");
var cnt = (int)cellXfs.Attribute("count");
cnt++;
cellXfs.Attribute("count").Value = cnt.ToString();
cellXfs.Add(
new XElement(S.xf,
new XAttribute("numFmtId", formatCodeToAdd),
new XAttribute("fontId", 0),
new XAttribute("fillId", 0),
new XAttribute("borderId", 0),
new XAttribute("applyNumberFormat", 1)));
return cnt - 1;
}
private static string RowColToString(int row, int col)
{
var str = SpreadsheetMLUtil.IntToColumnId(col) + (row + 1).ToString();
return str;
}
private static object UpdateAccentTransform(XNode node, int accentNumber)
{
XElement element = node as XElement;
if (element != null)
{
if (element.Name == A.schemeClr && (string)element.Attribute("val") == "accent1")
return new XElement(A.schemeClr, new XAttribute("val", "accent" + accentNumber));
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => UpdateAccentTransform(n, accentNumber)));
}
return node;
}
public static bool UpdateChart(PresentationDocument pDoc, int slideNumber, ChartData chartData)
{
var presentationPart = pDoc.PresentationPart;
var pXDoc = presentationPart.GetXDocument();
var sldIdElement = pXDoc.Root.Elements(P.sldIdLst).Elements(P.sldId).Skip(slideNumber - 1).FirstOrDefault();
if (sldIdElement != null)
{
var rId = (string)sldIdElement.Attribute(R.id);
var slidePart = presentationPart.GetPartById(rId);
var sXDoc = slidePart.GetXDocument();
var chartRid = (string)sXDoc.Descendants(C.chart).Attributes(R.id).FirstOrDefault();
if (chartRid != null)
{
ChartPart chartPart = (ChartPart)slidePart.GetPartById(chartRid);
UpdateChart(chartPart, chartData);
return true;
}
return true;
}
return false;
}
}
}