forked from ClosedXML/ClosedXML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XLCell.cs
3078 lines (2585 loc) · 112 KB
/
XLCell.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using FastMember;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace ClosedXML.Excel
{
using Attributes;
using ClosedXML.Extensions;
[DebuggerDisplay("{Address}")]
internal class XLCell : XLStylizedBase, IXLCell, IXLStylized
{
public static readonly DateTime BaseDate = new DateTime(1899, 12, 30);
private static readonly Regex A1Regex = new Regex(
@"(?<=\W)(\$?[a-zA-Z]{1,3}\$?\d{1,7})(?=\W)" // A1
+ @"|(?<=\W)(\$?\d{1,7}:\$?\d{1,7})(?=\W)" // 1:1
+ @"|(?<=\W)(\$?[a-zA-Z]{1,3}:\$?[a-zA-Z]{1,3})(?=\W)", RegexOptions.Compiled); // A:A
public static readonly Regex A1SimpleRegex = new Regex(
// @"(?<=\W)" // Start with non word
@"(?<Reference>" // Start Group to pick
+ @"(?<Sheet>" // Start Sheet Name, optional
+ @"("
+ @"\'([^\[\]\*/\\\?:\']+|\'\')\'"
// Sheet name with special characters, surrounding apostrophes are required
+ @"|"
+ @"\'?\w+\'?" // Sheet name with letters and numbers, surrounding apostrophes are optional
+ @")"
+ @"!)?" // End Sheet Name, optional
+ @"(?<Range>" // Start range
+ @"\$?[a-zA-Z]{1,3}\$?\d{1,7}" // A1 Address 1
+ @"(?<RangeEnd>:\$?[a-zA-Z]{1,3}\$?\d{1,7})?" // A1 Address 2, optional
+ @"|"
+ @"(?<ColumnNumbers>\$?\d{1,7}:\$?\d{1,7})" // 1:1
+ @"|"
+ @"(?<ColumnLetters>\$?[a-zA-Z]{1,3}:\$?[a-zA-Z]{1,3})" // A:A
+ @")" // End Range
+ @")" // End Group to pick
//+ @"(?=\W)" // End with non word
, RegexOptions.Compiled);
private static readonly Regex A1RowRegex = new Regex(
@"(\$?\d{1,7}:\$?\d{1,7})" // 1:1
, RegexOptions.Compiled);
private static readonly Regex A1ColumnRegex = new Regex(
@"(\$?[a-zA-Z]{1,3}:\$?[a-zA-Z]{1,3})" // A:A
, RegexOptions.Compiled);
private static readonly Regex R1C1Regex = new Regex(
@"(?<=\W)([Rr](?:\[-?\d{0,7}\]|\d{0,7})?[Cc](?:\[-?\d{0,7}\]|\d{0,7})?)(?=\W)" // R1C1
+ @"|(?<=\W)([Rr]\[?-?\d{0,7}\]?:[Rr]\[?-?\d{0,7}\]?)(?=\W)" // R:R
+ @"|(?<=\W)([Cc]\[?-?\d{0,5}\]?:[Cc]\[?-?\d{0,5}\]?)(?=\W)", RegexOptions.Compiled); // C:C
private static readonly Regex utfPattern = new Regex(@"(?<!_x005F)_x(?!005F)([0-9A-F]{4})_", RegexOptions.Compiled);
#region Fields
private string _cellValue = String.Empty;
private XLComment _comment;
private XLDataType _dataType;
private XLHyperlink _hyperlink;
private XLRichText _richText;
public bool SettingHyperlink;
internal int SharedStringId { get; set; }
private string _formulaA1;
private string _formulaR1C1;
#endregion Fields
#region Constructor
internal XLCell(XLWorksheet worksheet, XLAddress address, XLStyleValue styleValue)
: base(styleValue)
{
Address = address;
ShareString = true;
Worksheet = worksheet;
}
public XLCell(XLWorksheet worksheet, XLAddress address, IXLStyle style)
: this(worksheet, address, (style as XLStyle).Value)
{
}
public XLCell(XLWorksheet worksheet, XLAddress address)
: this(worksheet, address, XLStyle.Default.Value)
{
}
#endregion Constructor
public XLWorksheet Worksheet { get; private set; }
private int _rowNumber;
private int _columnNumber;
private bool _fixedRow;
private bool _fixedCol;
public XLAddress Address
{
get
{
return new XLAddress(Worksheet, _rowNumber, _columnNumber, _fixedRow, _fixedCol);
}
internal set
{
if (value == null)
return;
_rowNumber = value.RowNumber;
_columnNumber = value.ColumnNumber;
_fixedRow = value.FixedRow;
_fixedCol = value.FixedColumn;
}
}
public string InnerText
{
get
{
if (HasRichText)
return _richText.ToString();
return string.Empty == _cellValue ? FormulaA1 : _cellValue;
}
}
public IXLDataValidation NewDataValidation
{
get
{
return AsRange().NewDataValidation; // Call the data validation without breaking it into pieces
}
}
/// <summary>
/// Get the data validation rule containing current cell or create a new one if no rule was defined for cell.
/// </summary>
public IXLDataValidation DataValidation
{
get
{
return SetDataValidation();
}
}
internal XLComment Comment
{
get
{
if (_comment == null)
{
CreateComment();
}
return _comment;
}
}
internal XLComment CreateComment(int? shapeId = null)
{
_comment = new XLComment(this, shapeId: shapeId);
return _comment;
}
#region IXLCell Members
IXLDataValidation IXLCell.DataValidation
{
get { return DataValidation; }
}
IXLWorksheet IXLCell.Worksheet
{
get { return Worksheet; }
}
IXLAddress IXLCell.Address
{
get { return Address; }
}
IXLRange IXLCell.AsRange()
{
return AsRange();
}
public IXLCell SetValue<T>(T value)
{
return SetValue(value, true);
}
internal IXLCell SetValue<T>(T value, bool setTableHeader)
{
if (IsInferiorMergedCell())
return this;
if (value == null)
return this.Clear(XLClearOptions.Contents);
FormulaA1 = String.Empty;
_richText = null;
if (setTableHeader)
{
if (SetTableHeaderValue(value)) return this;
if (SetTableTotalsRowLabel(value)) return this;
}
var style = GetStyleForRead();
Boolean parsed;
string parsedValue;
// For SetValue<T> we set the cell value directly to the parameter
// as opposed to the other SetValue(object value) where we parse the string and try to decude the value
var tuple = SetKnownTypedValue(value, style, acceptString: true);
parsedValue = tuple.Item1;
parsed = tuple.Item2;
// If parsing was unsuccessful, we throw an ArgumentException
// because we are using SetValue<T> (typed).
// Only in SetValue(object value) to we try to fall back to a value of a different type
if (!parsed)
throw new ArgumentException($"Unable to set cell value to {value.ToInvariantString()}");
SetInternalCellValueString(parsedValue, validate: true, parseToCachedValue: false);
CachedValue = null;
return this;
}
// TODO: Replace with (string, bool) ValueTuple later
private Tuple<string, bool> SetKnownTypedValue<T>(T value, XLStyleValue style, Boolean acceptString)
{
string parsedValue;
bool parsed;
if (value is String && acceptString || value is char || value is Guid || value is Enum)
{
parsedValue = value.ToInvariantString();
_dataType = XLDataType.Text;
if (parsedValue.Contains(Environment.NewLine) && !style.Alignment.WrapText)
Style.Alignment.WrapText = true;
parsed = true;
}
else if (value.Equals(DBNull.Value))
{
parsedValue = "";
_dataType = XLDataType.Text;
parsed = true;
}
else if (value is DateTime d && d >= BaseDate)
{
parsedValue = d.ToOADate().ToInvariantString();
parsed = true;
SetDateTimeFormat(style, d.Date == d);
}
else if (value is TimeSpan ts)
{
parsedValue = ts.TotalDays.ToInvariantString();
parsed = true;
SetTimeSpanFormat(style);
}
else if (value is Boolean b)
{
parsedValue = b ? "1" : "0";
_dataType = XLDataType.Boolean;
parsed = true;
}
else if (value.IsNumber())
{
if (
(value is double d1 && (double.IsNaN(d1) || double.IsInfinity(d1)))
|| (value is float f && (float.IsNaN(f) || float.IsInfinity(f)))
)
{
parsedValue = value.ToString();
_dataType = XLDataType.Text;
parsed = parsedValue.Length != 0;
}
else
{
parsedValue = value.ToInvariantString();
_dataType = XLDataType.Number;
}
parsed = true;
}
else
{
parsed = false;
parsedValue = null;
}
return new Tuple<string, bool>(parsedValue, parsed);
}
private string DeduceCellValueByParsing(string value, XLStyleValue style)
{
if (String.IsNullOrEmpty(value))
{
_dataType = XLDataType.Text;
}
else if (value[0] == '\'')
{
// If a user sets a cell value to a value starting with a single quote
// ensure the data type is text
// and that it will be prefixed with a quote in Excel too
value = value.Substring(1, value.Length - 1);
_dataType = XLDataType.Text;
if (value.Contains(Environment.NewLine) && !style.Alignment.WrapText)
Style.Alignment.WrapText = true;
this.Style.SetIncludeQuotePrefix();
}
else if (value.Trim() != "NaN" && Double.TryParse(value, XLHelper.NumberStyle, XLHelper.ParseCulture, out Double _))
_dataType = XLDataType.Number;
else if (TimeSpan.TryParse(value, out TimeSpan ts))
{
value = ts.ToInvariantString();
SetTimeSpanFormat(style);
}
else if (DateTime.TryParse(value, out DateTime dt) && dt >= BaseDate)
{
value = dt.ToOADate().ToInvariantString();
SetDateTimeFormat(style, dt.Date == dt);
}
else if (Boolean.TryParse(value, out Boolean b))
{
value = b ? "1" : "0";
_dataType = XLDataType.Boolean;
}
else
{
_dataType = XLDataType.Text;
if (value.Contains(Environment.NewLine) && !style.Alignment.WrapText)
Style.Alignment.WrapText = true;
}
return value;
}
public T GetValue<T>()
{
if (TryGetValue(out T retVal))
return retVal;
throw new FormatException($"Cannot convert {this.Address.ToStringRelative(true)}'s value to " + typeof(T));
}
public string GetString()
{
return GetValue<string>();
}
public double GetDouble()
{
return GetValue<double>();
}
public bool GetBoolean()
{
return GetValue<bool>();
}
public DateTime GetDateTime()
{
return GetValue<DateTime>();
}
public TimeSpan GetTimeSpan()
{
return GetValue<TimeSpan>();
}
public string GetFormattedString()
{
var format = GetFormat();
try
{
return Value.ToExcelFormat(format);
}
catch { }
try
{
return CachedValue.ToExcelFormat(format);
}
catch { }
return _cellValue;
}
/// <summary>
/// Flag showing that the cell is in formula evaluation state.
/// </summary>
internal bool IsEvaluating { get; private set; }
/// <summary>
/// Calculate a value of the specified formula.
/// </summary>
/// <param name="fA1">Cell formula to evaluate.</param>
/// <returns>Null if formula is empty or null, calculated value otherwise.</returns>
private object RecalculateFormula(string fA1)
{
if (string.IsNullOrEmpty(fA1))
return null;
if (IsEvaluating)
throw new InvalidOperationException("Circular Reference");
if (fA1[0] == '{')
fA1 = fA1.Substring(1, fA1.Length - 2);
string sName;
string cAddress;
if (fA1.Contains('!'))
{
sName = fA1.Substring(0, fA1.IndexOf('!'));
if (sName[0] == '\'')
sName = sName.Substring(1, sName.Length - 2);
cAddress = fA1.Substring(fA1.IndexOf('!') + 1);
}
else
{
sName = Worksheet.Name;
cAddress = fA1;
}
if (Worksheet.Workbook.WorksheetsInternal.Any<XLWorksheet>(
w => String.Compare(w.Name, sName, true) == 0)
&& XLHelper.IsValidA1Address(cAddress)
)
{
var referenceCell = Worksheet.Workbook.Worksheet(sName).Cell(cAddress);
if (referenceCell.IsEmpty(XLCellsUsedOptions.AllContents))
return 0;
else
return referenceCell.Value;
}
object retVal;
try
{
IsEvaluating = true;
if (Worksheet
.Workbook
.WorksheetsInternal
.Any<XLWorksheet>(w => String.Compare(w.Name, sName, true) == 0)
&& XLHelper.IsValidA1Address(cAddress))
{
var referenceCell = Worksheet.Workbook.Worksheet(sName).Cell(cAddress);
if (referenceCell.IsEmpty(XLCellsUsedOptions.AllContents))
return 0;
else
return referenceCell.Value;
}
retVal = Worksheet.Evaluate(fA1);
}
finally
{
IsEvaluating = false;
}
if (retVal is IEnumerable retValEnumerable && !(retVal is String))
return retValEnumerable.Cast<object>().First();
return retVal;
}
public void InvalidateFormula()
{
NeedsRecalculation = true;
Worksheet.Workbook.InvalidateFormulas();
ModifiedAtVersion = Worksheet.Workbook.RecalculationCounter;
}
/// <summary>
/// Perform an evaluation of cell formula. If cell does not contain formula nothing happens, if cell does not need
/// recalculation (<see cref="NeedsRecalculation"/> is False) nothing happens either, unless <paramref name="force"/> flag is specified.
/// Otherwise recalculation is perfomed, result value is preserved in <see cref="CachedValue"/> and returned.
/// </summary>
/// <param name="force">Flag indicating whether a recalculation must be performed even is cell does not need it.</param>
/// <returns>Null if cell does not contain a formula. Calculated value otherwise.</returns>
public Object Evaluate(Boolean force = false)
{
if (force || NeedsRecalculation)
{
if (HasFormula)
{
CachedValue = RecalculateFormula(FormulaA1);
UpdateCachedValueFromDataType();
}
else
CachedValue = null;
EvaluatedAtVersion = Worksheet.Workbook.RecalculationCounter;
NeedsRecalculation = false;
}
return CachedValue;
}
internal void SetInternalCellValueString(String cellValue)
{
SetInternalCellValueString(cellValue, validate: false, parseToCachedValue: this.HasFormula);
}
private void SetInternalCellValueString(String cellValue, Boolean validate, Boolean parseToCachedValue)
{
if (validate)
{
if (cellValue.Length > 32767) throw new ArgumentOutOfRangeException(nameof(cellValue), "Cells can hold a maximum of 32,767 characters.");
}
this._cellValue = cellValue;
if (parseToCachedValue)
CachedValue = ParseCellValueFromString();
}
private void UpdateCachedValueFromDataType()
{
if (CachedValue is double d)
{
if (this.DataType == XLDataType.DateTime && d.IsValidOADateNumber())
CachedValue = DateTime.FromOADate(d);
else if (this.DataType == XLDataType.TimeSpan)
CachedValue = TimeSpan.FromDays(d);
}
else if (CachedValue is DateTime dt)
{
if (this.DataType == XLDataType.Number)
CachedValue = dt.ToOADate();
else if (this.DataType == XLDataType.TimeSpan)
CachedValue = TimeSpan.FromDays(dt.ToOADate());
}
else if (CachedValue is TimeSpan ts)
{
if (this.DataType == XLDataType.DateTime)
CachedValue = DateTime.FromOADate(ts.TotalDays);
else if (this.DataType == XLDataType.Number)
CachedValue = ts.TotalDays;
}
}
internal void SetDataTypeFast(XLDataType dataType)
{
this._dataType = dataType;
}
private Object ParseCellValueFromString()
{
return ParseCellValueFromString(_cellValue, _dataType, out String error);
}
private Object ParseCellValueFromString(String cellValue, XLDataType dataType, out String error)
{
error = "";
if ("" == cellValue)
return "";
if (dataType == XLDataType.Boolean)
{
if (bool.TryParse(cellValue, out Boolean b))
return b;
else if (cellValue == "0")
return false;
else if (cellValue == "1")
return true;
else
return !string.IsNullOrEmpty(cellValue);
}
if (dataType == XLDataType.DateTime)
{
if (Double.TryParse(cellValue, XLHelper.NumberStyle, XLHelper.ParseCulture, out Double d))
{
if (d.IsValidOADateNumber())
return DateTime.FromOADate(d);
else
return d;
}
else if (DateTime.TryParse(cellValue, out DateTime dt))
return dt;
else
{
error = string.Format("Cannot set data type to DateTime because '{0}' is not recognized as a date.", cellValue);
return null;
}
}
if (dataType == XLDataType.Number)
{
var v = cellValue;
Double factor = 1.0;
if (v.EndsWith("%"))
{
v = v.Substring(0, v.Length - 1);
factor = 1 / 100.0;
}
if (Double.TryParse(v, XLHelper.NumberStyle, CultureInfo.InvariantCulture, out Double d))
return d * factor;
else
{
error = string.Format("Cannot set data type to Number because '{0}' is not recognized as a number.", cellValue);
return null;
}
}
if (dataType == XLDataType.TimeSpan)
{
if (TimeSpan.TryParse(cellValue, out TimeSpan ts))
return ts;
else if (Double.TryParse(cellValue, XLHelper.NumberStyle, XLHelper.ParseCulture, out Double d))
return TimeSpan.FromDays(d);
else
{
error = string.Format("Cannot set data type to TimeSpan because '{0}' is not recognized as a TimeSpan.", cellValue);
return null;
}
}
return cellValue;
}
public object Value
{
get
{
if (!String.IsNullOrWhiteSpace(_formulaA1) ||
!String.IsNullOrEmpty(_formulaR1C1))
{
return Evaluate();
}
var cellValue = HasRichText ? _richText.ToString() : _cellValue;
return ParseCellValueFromString(cellValue, _dataType, out _);
}
set
{
if (IsInferiorMergedCell())
return;
FormulaA1 = String.Empty;
if (value is XLCells) throw new ArgumentException("Cannot assign IXLCells object to the cell value.");
if (SetTableHeaderValue(value)) return;
if (SetRangeRows(value)) return;
if (SetRangeColumns(value)) return;
if (SetDataTable(value)) return;
if (SetEnumerable(value)) return;
if (SetRange(value)) return;
if (!SetRichText(value))
SetValue(value);
CachedValue = null;
if (_cellValue.Length > 32767) throw new ArgumentOutOfRangeException(nameof(value), "Cells can hold only 32,767 characters.");
}
}
public IXLTable InsertTable<T>(IEnumerable<T> data)
{
return InsertTable(data, null, true);
}
public IXLTable InsertTable<T>(IEnumerable<T> data, bool createTable)
{
return InsertTable(data, null, createTable);
}
public IXLTable InsertTable<T>(IEnumerable<T> data, string tableName)
{
return InsertTable(data, tableName, true);
}
public IXLTable InsertTable<T>(IEnumerable<T> data, String tableName, Boolean createTable)
{
return InsertTable(data, tableName, createTable, addHeadings: true, transpose: false);
}
public IXLTable InsertTable<T>(IEnumerable<T> data, String tableName, Boolean createTable, Boolean addHeadings, Boolean transpose)
{
if (createTable && this.Worksheet.Tables.Any(t => t.Contains(this)))
throw new InvalidOperationException(String.Format("This cell '{0}' is already part of a table.", this.Address.ToString()));
var range = InsertDataInternal(data, addHeadings, transpose);
if (createTable)
// Create a table and save it in the file
return tableName == null ? range.CreateTable() : range.CreateTable(tableName);
else
// Create a table, but keep it in memory. Saved file will contain only "raw" data and column headers
return tableName == null ? range.AsTable() : range.AsTable(tableName);
}
public IXLTable InsertTable(DataTable data)
{
return InsertTable(data, null, true);
}
public IXLTable InsertTable(DataTable data, Boolean createTable)
{
return InsertTable(data, null, createTable);
}
public IXLTable InsertTable(DataTable data, String tableName)
{
return InsertTable(data, tableName, true);
}
public IXLTable InsertTable(DataTable data, String tableName, Boolean createTable)
{
if (data == null || data.Columns.Count == 0)
return null;
if (createTable && this.Worksheet.Tables.Any(t => t.Contains(this)))
throw new InvalidOperationException(String.Format("This cell '{0}' is already part of a table.", this.Address.ToString()));
if (data.Rows.Cast<DataRow>().Any())
return InsertTable(data.Rows.Cast<DataRow>(), tableName, createTable);
var co = _columnNumber;
foreach (DataColumn col in data.Columns)
{
Worksheet.SetValue(col.ColumnName, _rowNumber, co);
co++;
}
ClearMerged();
var range = Worksheet.Range(
_rowNumber,
_columnNumber,
_rowNumber,
co - 1);
if (createTable)
// Create a table and save it in the file
return tableName == null ? range.CreateTable() : range.CreateTable(tableName);
else
// Create a table, but keep it in memory. Saved file will contain only "raw" data and column headers
return tableName == null ? range.AsTable() : range.AsTable(tableName);
}
internal XLRange InsertDataInternal<T>(IEnumerable<T> data, Boolean addHeadings, Boolean transpose)
{
if (data == null || data is String)
return null;
var currentRowNumber = _rowNumber;
if (addHeadings && !transpose) currentRowNumber++;
var currentColumnNumber = _columnNumber;
if (addHeadings && transpose) currentColumnNumber++;
var firstRowNumber = _rowNumber;
var hasHeadings = false;
var maximumColumnNumber = currentColumnNumber;
var maximumRowNumber = currentRowNumber;
var itemType = data.GetItemType();
var isArray = itemType.IsArray;
var isDataTable = itemType == typeof(DataTable);
var isDataReader = itemType == typeof(IDataReader);
// Inline functions to handle looping with transposing
//////////////////////////////////////////////////////
void incrementFieldPosition()
{
if (transpose)
{
maximumRowNumber = Math.Max(maximumRowNumber, currentRowNumber);
currentRowNumber++;
}
else
{
maximumColumnNumber = Math.Max(maximumColumnNumber, currentColumnNumber);
currentColumnNumber++;
}
}
void incrementRecordPosition()
{
if (transpose)
{
maximumColumnNumber = Math.Max(maximumColumnNumber, currentColumnNumber);
currentColumnNumber++;
}
else
{
maximumRowNumber = Math.Max(maximumRowNumber, currentRowNumber);
currentRowNumber++;
}
}
void resetRecordPosition()
{
if (transpose)
currentRowNumber = _rowNumber;
else
currentColumnNumber = _columnNumber;
}
//////////////////////////////////////////////////////
if (!data.Any())
{
if (itemType.IsSimpleType())
maximumColumnNumber = _columnNumber;
else
maximumColumnNumber = _columnNumber + itemType.GetFields().Length + itemType.GetProperties().Length - 1;
}
else if (itemType.IsSimpleType())
{
foreach (object o in data)
{
resetRecordPosition();
if (addHeadings && !hasHeadings)
{
var fieldName = XLColumnAttribute.GetHeader(itemType);
if (String.IsNullOrWhiteSpace(fieldName))
fieldName = itemType.Name;
Worksheet.SetValue(fieldName, firstRowNumber, currentColumnNumber);
hasHeadings = true;
resetRecordPosition();
}
Worksheet.SetValue(o, currentRowNumber, currentColumnNumber);
incrementFieldPosition();
incrementRecordPosition();
}
}
else
{
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
var memberCache = new Dictionary<Type, IEnumerable<MemberInfo>>();
var accessorCache = new Dictionary<Type, TypeAccessor>();
IEnumerable<MemberInfo> members = null;
TypeAccessor accessor = null;
bool isPlainObject = itemType == typeof(object);
if (!isPlainObject)
{
members = itemType.GetFields(bindingFlags).Cast<MemberInfo>()
.Concat(itemType.GetProperties(bindingFlags))
.Where(mi => !XLColumnAttribute.IgnoreMember(mi))
.OrderBy(mi => XLColumnAttribute.GetOrder(mi));
accessor = TypeAccessor.Create(itemType);
}
foreach (T m in data)
{
resetRecordPosition();
if (m.GetType().IsSimpleType())
{
if (addHeadings && !hasHeadings)
{
var fieldName = XLColumnAttribute.GetHeader(itemType);
if (String.IsNullOrWhiteSpace(fieldName))
fieldName = itemType.Name;
Worksheet.SetValue(fieldName, firstRowNumber, currentColumnNumber);
hasHeadings = true;
resetRecordPosition();
}
Worksheet.SetValue(m as object, currentRowNumber, currentColumnNumber);
incrementFieldPosition();
}
else
{
if (isPlainObject)
{
// In this case data is just IEnumerable<object>, which means we have to determine the runtime type of each element
// This is very inefficient and we prefer type of T to be a concrete class or struct
var type = m.GetType();
isArray |= type.IsArray;
isDataTable |= type == typeof(DataRow);
isDataReader |= type == typeof(IDataRecord);
if (!memberCache.ContainsKey(type))
{
var _accessor = TypeAccessor.Create(type);
var _members = type.GetFields(bindingFlags).Cast<MemberInfo>()
.Concat(type.GetProperties(bindingFlags))
.Where(mi => !XLColumnAttribute.IgnoreMember(mi))
.OrderBy(mi => XLColumnAttribute.GetOrder(mi));
memberCache.Add(type, _members);
accessorCache.Add(type, _accessor);
}
members = memberCache[type];
accessor = accessorCache[type];
}
if (isArray)
{
foreach (var item in (m as Array))
{
Worksheet.SetValue(item, currentRowNumber, currentColumnNumber);
incrementFieldPosition();
}
}
else if (isDataTable || m is DataRow)
{
var row = m as DataRow;
if (!isDataTable)
isDataTable = true;
if (addHeadings && !hasHeadings)
{
foreach (var fieldName in from DataColumn column in row.Table.Columns
select String.IsNullOrWhiteSpace(column.Caption)
? column.ColumnName
: column.Caption)
{
Worksheet.SetValue(fieldName, firstRowNumber, currentColumnNumber);
incrementFieldPosition();
}
resetRecordPosition();
hasHeadings = true;
}
foreach (var item in row.ItemArray)
{
Worksheet.SetValue(item, currentRowNumber, currentColumnNumber);
incrementFieldPosition();
}
}
else if (isDataReader || m is IDataRecord)
{
if (!isDataReader)
isDataReader = true;
var record = m as IDataRecord;
var fieldCount = record.FieldCount;
if (addHeadings && !hasHeadings)
{
for (var i = 0; i < fieldCount; i++)
{
Worksheet.SetValue(record.GetName(i), firstRowNumber, currentColumnNumber);
incrementFieldPosition();
}
resetRecordPosition();
hasHeadings = true;
}
for (var i = 0; i < fieldCount; i++)
{
Worksheet.SetValue(record[i], currentRowNumber, currentColumnNumber);
incrementFieldPosition();
}
}
else
{
if (addHeadings && !hasHeadings)
{
foreach (var mi in members)
{
if (!(mi is IEnumerable))
{
var fieldName = XLColumnAttribute.GetHeader(mi);
if (String.IsNullOrWhiteSpace(fieldName))
fieldName = mi.Name;
Worksheet.SetValue(fieldName, firstRowNumber, currentColumnNumber);
}