-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxl.nim
3749 lines (3075 loc) · 117 KB
/
xl.nim
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
#====================================================================
#
# Xl - Open XML Spreadsheet (Excel) Library for Nim
# Copyright (c) Chen Kai-Hung, Ward
#
#====================================================================
## Open XML Spreadsheet (Excel) Library for Nim.
# TODO
# - freeze panes
# - cell selection
# - image? comment? chart?
import xl/private/xn
import zippy/ziparchives
import std/[strutils, os, tables, options, strscans, strtabs, algorithm,
critbits, sets, hashes, streams, times, math]
template `/`(x: string): string =
'/' & x
template `/`(x, y: string): string =
x & '/' & y
template `/../`(head, tail: string): string =
os.`/../`(head, tail).replace("\\", "/")
const
NsMain = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
NsContentTypes = "http://schemas.openxmlformats.org/package/2006/content-types"
NsRelationships = "http://schemas.openxmlformats.org/package/2006/relationships"
NsDocumentRelationships = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
NsCoreProperties = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
NsExtendedProperties = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"
NsDc = "http://purl.org/dc/elements/1.1/"
NsDcTerms = "http://purl.org/dc/terms/"
NsXSI = "http://www.w3.org/2001/XMLSchema-instance"
TypeHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
TypeWorksheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
TypeStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
TypeSharedStrings = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"
TypeOfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
TypeCoreProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"
TypeExtendedProperties = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"
MimeXml = "application/xml"
MimeWorksheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"
MimeStyles = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"
MimeSharedStrings = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"
MimeRelationships = "application/vnd.openxmlformats-package.relationships+xml"
MimeCoreProperties = "application/vnd.openxmlformats-package.core-properties+xml"
MimeExtendedProperties = "application/vnd.openxmlformats-officedocument.extended-properties+xml"
MimeSheetMain = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"
MimeTemplateMain = "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
MimeCalcChain = "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml"
Xl = "xl"
DocPropsApp = "docProps/app.xml"
DocPropsCore = "docProps/core.xml"
Workbook = Xl/"workbook.xml"
SharedStrings = Xl/"sharedStrings.xml"
Styles = Xl/"styles.xml"
ContentTypes = "[Content_Types].xml"
BuiltinFormats = [
"General", "0", "0.00", "#,##0", "#,##0.00", "($#,##0_);($#,##0)",
"($#,##0_);[Red]($#,##0)", "($#,##0.00_);($#,##0.00)", "($#,##0.00_);[Red]($#,##0.00)",
"0%", "0.00%", "0.00E+00", "# ?/?", "# ??/??", "m/d/yy", "d-mmm-yy", "d-mmm", "mmm-yy",
"h:mm AM/PM", "h:mm:ss AM/PM", "h:mm", "h:mm:ss", "m/d/yy h:mm", "General", "General",
"General", "General", "General", "General", "General", "General", "General", "General",
"General", "General", "General", "General", "(#,##0_);(#,##0)", "(#,##0_);[Red](#,##0)",
"(#,##0.00_);(#,##0.00)", "(#,##0.00_);[Red](#,##0.00)",
"_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",
"_($* #,##0_);_($* (#,##0);_($* \"-\"_);_(@_)",
"_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",
"_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)",
"mm:ss", "[h]:mm:ss", "mm:ss.0", "##0.0E+0", "@"
]
type
XlCellType = enum
ctNumber = "n"
ctSharedString = "s"
ctBoolean = "b"
ctError = "e"
ctInlineStr = "inlineStr"
ctStr = "str"
XlError* = object of CatchableError
## Default error object.
XlRC* = tuple[row: int, col: int]
## Represent a cell position.
XlRCRC* = tuple[first: XlRC, last: XlRC]
## Represent a range.
XlObject = ref object
raw: string
xn: XlNode
postProcess: (string, string)
XlChange = ref object
numFmt: Option[XlNumFmt]
font: Option[XlFont]
fill: Option[XlFill]
border: Option[XlBorder]
alignment: Option[XlAlignment]
protection: Option[XlProtection]
XlSharedStrings = object
xSharedStrings: XlNode
table: OrderedTable[string, tuple[index: int, isNew: bool]]
newCount: int
XlSharedStyles = object
xStyles: XlNode
styles: OrderedTable[tuple[oldStyle: int, change: XlChange], int]
numFmts: Table[XlNumFmt, int]
fonts: Table[XlFont, int]
fills: Table[XlFill, int]
borders: Table[Xlborder, int]
xfCount: int
XlRel = object
typ: string
target: string
external: bool
XlType = object
typ: string
override: bool
XlRels = Table[string, XlRel]
XlTypes = Table[string, XlType]
XlProperties* = object
## Represent workbook properties.
title*: string
subject*: string
creator*: string
keywords*: string
description*: string
lastModifiedBy*: string
created*: string
modified*: string
category*: string
contentStatus*: string
application*: string
manager*: string
company*: string
XlSheetProtection* = object
## Represent sheet protection properties.
sheet*: Option[bool]
objects*: Option[bool]
scenarios*: Option[bool]
selectLockedCells*: Option[bool]
selectUnlockedCells*: Option[bool]
formatCells*: Option[bool]
formatColumns*: Option[bool]
formatRows*: Option[bool]
insertColumns*: Option[bool]
insertRows*: Option[bool]
insertHyperlinks*: Option[bool]
deleteColumns*: Option[bool]
deleteRows*: Option[bool]
sort*: Option[bool]
autoFilter*: Option[bool]
pivotTables*: Option[bool]
password*: Option[string]
XlWorkbook* = ref object
## Represent a workbook.
contents: Table[string, XlObject]
sheets: seq[XlSheet]
sharedStrings: XlSharedStrings
sharedStyles: XlSharedStyles
rels: XlRels
types: XlTypes
properties: XlProperties
active: int
experimental: bool
XlSheet* = ref object
## Represent a worksheet.
workbook: XlWorkbook
obj: XlObject
name: string
hidden: bool
color: XlColor
protection: XlSheetProtection
cells: Table[XlRC, XlCell]
rows: Table[int, XlRow]
cols: Table[int, XlCol]
merges: HashSet[XlRCRC]
rels: XlRels
first: XlRC
last: XlRC
XlRange* = ref object
## Represent a rectangle range.
sheet: XlSheet
first: XlRC
last: XlRC
turned: bool
XlCollection* = ref object
## Represent a collection of cells.
sheet: XlSheet
rcs: HashSet[XlRC]
XlStylable = ref object of RootRef
sheet: XlSheet
change: XlChange
style: int
XlRow* = ref object of XlStylable
## Represent a row of a sheet.
row: int
height: float
hidden: bool
outlineLevel: int
collapsed: bool
thickTop: bool
thickBot: bool
ph: bool
XlCol* = ref object of XlStylable
## Represent a column of a sheet.
col: int
width: float
hidden: bool
XlCell* = ref object of XlStylable
## Represent a cell of a sheet.
rc: XlRC
formula: string
value: string
hyperlink: string
riches: XlRiches
ct: XlCellType
readonly: bool
XlNumFmt* = object
## Represent number format.
code*: Option[string]
XlColor* = object
## Represent a color.
##
## Possible values of rgb:
## 6 or 8 hexdigits presents RGB or ARGB color.
##
## Possible values of indexed:
## `0`..`64` system default color index.
##
## Possible values of tint:
## `-1.0`..`1.0`.
`auto`*: Option[bool]
rgb*: Option[string]
theme*: Option[int]
indexed*: Option[int]
tint*: Option[float]
XlFont* = object
## Represent font style.
##
## Possible values of family:
## `0`..`14`.
##
## Possible values of underline:
## `""`, `"single"`, `"double"`, `"singleAccounting"`, `"doubleAccounting"`.
##
## Possible values of vertAlign:
## `"superscript"`, `"subscript"`, `"baseline"`.
##
## Possible values of scheme:
## `"major"`, `"minor"`.
name*: Option[string]
charset*: Option[int]
family*: Option[int]
size*: Option[float]
bold*: Option[bool]
italic*: Option[bool]
strike*: Option[bool]
underline*: Option[string]
vertAlign*: Option[string]
color*: Option[XlColor]
scheme*: Option[string]
XlGradient* = object
## Represent gradient fill style.
##
## Possible values of gradientType:
## `"linear"`, `"path"`.
gradientType*: Option[string]
degree*: Option[float]
left*, right*, top*, bottom*: Option[float]
stops*: seq[XlColor]
XlPattern* = object
## Represent pattern fill style.
##
## Possible values of patternType:
## `"none"`, `"solid"`, `"mediumGray"`, `"darkGray"`, `"lightGray"`,
## `"darkHorizontal"`, `"darkVertical"`, `"darkDown"`, `"darkUp"`,
## `"darkGrid"`, `"darkTrellis"`, `"lightHorizontal"`, `"lightVertical"`,
## `"lightDown"`, `"lightUp"`, `"lightGrid"`, `"lightTrellis"`, `"gray125"`,
## `"gray0625"`.
patternType*: Option[string]
fgColor*: Option[XlColor]
bgColor*: Option[XlColor]
XlFill* = object
## Represent fill style.
patternFill*: Option[XlPattern]
gradientFill*: Option[XlGradient]
XlAlignment* = object
## Represent alignment style.
##
## Possible values of horizontal:
## `"general"`, `"left"`, `"center"`, `"right"`, `"fill"`, `"justify"`,
## `"centerContinuous"`, `"distributed"`.
##
## Possible values of vertical:
## `"top"`, `"center"`, `"bottom"`, `"justify"`, `"distributed"`.
##
## Possible values of textRotation:
## `-90`..`180` or `255` (vertical text).
horizontal*: Option[string]
vertical*: Option[string]
textRotation*: Option[int]
wrapText*: Option[bool]
shrinkToFit*: Option[bool]
indent*: Option[int]
relativeIndent*: Option[int]
justifyLastLine*: Option[bool]
readingOrder*: Option[int]
verticalText*: Option[bool]
XlProtection* = object
## Represent protection setting.
locked*: Option[bool]
hidden*: Option[bool]
XlSide* = object
## Represent a side of border.
##
## Possible values of style:
## `"dashDot"`, `"dashDotDot"`, `"dashed"`, `"dotted"`, `"double"`,
## `"hair"`, `"medium"`, `"mediumDashDot"`, `"mediumDashDotDot"`,
## `"mediumDashed"`, `"slantDashDot"`, `"thick"`, `"thin"`.
style*: Option[string]
color*: Option[XlColor]
XlBorder* = object
## Represent border style.
outline*: Option[bool]
diagonalUp*: Option[bool]
diagonalDown*: Option[bool]
left*: Option[XlSide]
right*: Option[XlSide]
top*: Option[XlSide]
bottom*: Option[XlSide]
diagonal*: Option[XlSide]
vertical*: Option[XlSide]
horizontal*: Option[XlSide]
XlStyle* = object
## Represent all styles.
numFmt*: XlNumFmt
font*: XlFont
fill*: XlFill
border*: XlBorder
alignment*: XlAlignment
protection*: XlProtection
XlRich = tuple
text: string
font: XlFont
XlRiches* = seq[XlRich]
## Represent rich string styles.
const
EmptyRowCol = XlRC (-1, -1)
converter toSomeOption*[T: bool|int|float|string|XlColor|XlSide|XlPattern|XlGradient](x: T): Option[T] {.inline.} =
## Syntactic sugar for option type to avoid trivial `some`.
some x
# for XlChange ref type in hashtable
proc `==`(x, y: XlChange): bool =
if x.isNil and y.isNil:
return true
elif (x.isNil and not y.isNil) or (y.isNil and not x.isNil):
return false
else:
return x[] == y[]
# for XlChange ref type in hashtable
proc hash(x: XlChange): Hash {.inline.} =
if x.isNil:
return hash(cast[pointer](x))
else:
return hash(x[])
iterator sortedItems[A](t: HashSet[A]): A =
var s = newSeqOfCap[A](t.len)
for i in t: s.add i
s.sort()
for i in s: yield i
iterator sortedKeys[A, B](t: Table[A, B]): lent A =
var keys: seq[A]
for k in t.keys: keys.add k
keys.sort()
for k in keys: yield k
iterator sortedValues[A, B](t: var Table[A, B]): lent B =
# var keys = newSeqOfCap[A](t.len)
# for k in t.keys: keys.add k
# keys.sort()
# for k in keys: yield t[k]
var s = newSeqOfCap[(A, ptr B)](t.len)
for k, v in t.mpairs:
s.add (k, addr v)
s.sort() do (a, b: (A, ptr B)) -> int:
system.cmp(a[0], b[0])
for p in s:
yield p[1][]
iterator sortedPairs[A, B](t: var Table[A, B]): (A, var B) =
var s = newSeqOfCap[(A, ptr B)](t.len)
for k, v in t.mpairs:
s.add (k, addr v)
s.sort() do (a, b: (A, ptr B)) -> int:
system.cmp(a[0], b[0])
for p in s:
yield (p[0], p[1][])
template hasBoolOptionAttr(x: XlNode, attr: XlNsName|string): Option[bool] =
let val = x[attr]
case val
of "true":
some(true)
of "false":
some(false)
of "":
none(bool)
else:
try:
some((bool parseInt(val)))
except:
none(bool)
proc `[]=`[T](x: XlNode, key: string, opt: Option[T]) {.inline.} =
if opt.isSome:
when T is string|SomeNumber:
x[key] = $opt.get
elif T is bool:
x[key] = $opt.get.int
else:
{.error: "unknow type " & $T.}
proc expand(x: XlNode, ns: string, order: openarray[string]) =
var
cursor = 0
index = 0
while cursor < order.len:
if index >= x.count:
discard x.addChildXlNode(ns\order[cursor])
elif x[index].tag.ns != ns: # skip tag for other namespace
index.inc
continue
elif x[index].tag != ns\order[cursor]:
discard x.addChildXlNode(ns\order[cursor], index)
cursor.inc
index.inc
proc shrink(x: XlNode, ns: string, preserves: openarray[string]) =
for i in countdown(x.count - 1, 0):
let child = x[i]
var isDelete = true
if child.count == 0 and (child.attrs == nil or child.attrs.len == 0):
for tag in preserves:
if child.tag == ns\tag:
isDelete = false
break
if isDelete:
x.delete(i)
proc updateCount(x: XlNode) {.inline.} =
x["count"] = $x.count
proc parse(x: XlObject) =
if x.raw != "" and x.xn.isNil:
x.xn = parseXn(x.raw)
x.raw = ""
proc newXlObject(x: sink XlNode): XlObject {.inline.} =
result = XlObject(xn: x)
proc newXlObject(raw: sink string): XlObject {.inline.} =
result = XlObject(raw: raw)
proc rc*(name: string): XlRC =
## Convert cell reference (e.g. "A1") to XlRC tuple.
let name = name.toUpperAscii
var col, row, idx = 0
if scanp(name, idx,
+{'A'..'Z'} -> (col = col * 26 + ord($_) - ord('A') + 1),
+{'0'..'9'} -> (row = row * 10 + ord($_) - ord('0'))):
result.row = row
result.col = col
result.row.dec
result.col.dec
if result.row < 0 or result.col < 0:
raise newException(XlError, "invalid cell name")
proc rc*(xc: XlCell): XlRC {.inline.} =
## Return XlRC tuple of a cell.
result = xc.rc
proc rcrc*(name: string): XlRCRC =
## Convert range reference (e.g. "A1:C3") to XlRCRC tuple.
let sp = name.split(':', maxsplit=1)
if sp.len == 2:
result[0] = sp[0].rc
result[1] = sp[1].rc
else:
result[0] = name.rc
result[1] = result[0]
proc rcrc*(xr: XlRange): XlRCRC {.inline.} =
## Return XlRCRC tuple of a XlRange object.
result = (xr.first, xr.last)
proc name*(rc: XlRC): string =
## Convert a XlRC tuple to named reference (e.g. "A1").
if rc.row < 0 or rc.col < 0:
raise newException(XlError, "invalid XlRowCol")
var col = rc.col
while col >= 0:
result.insert $(chr('A'.ord + col mod 26))
col = col div 26 - 1
result.add $(rc.row + 1)
proc name*(rcrc: XlRCRC): string {.inline.} =
## Convert a XlRCRC tuple to range reference (e.g. "A1:C3").
result = rcrc[0].name
result.add ':'
result.add rcrc[1].name
proc name*(xc: XlCell): string {.inline.} =
## Return named reference of a cell.
result = xc.rc.name
proc value*(x: XlRow): int {.inline.} =
## Return row index value of a XlRow object.
result = x.row
proc value*(x: XlCol): int {.inline.} =
## Return col index value of a XlCol object.
result = x.col
proc len*(xs: XlSheet): int {.inline.} =
## Return total cells count of a sheet.
result = xs.cells.len
proc count*(xs: XlSheet): int {.inline.} =
## Return total cells count of a sheet.
result = xs.cells.len
proc isEmpty*(xr: XlRange): bool {.inline.} =
## Check if a XlRange object is empty or not.
result = xr.first.row < 0 or xr.first.col < 0 or
xr.last.row < 0 or xr.last.col < 0
proc isEmpty*(xs: XlSheet): bool {.inline.} =
## Check if a sheet is empty or not.
result = xs.count == 0
proc `$`(x: XlObject): string =
if x.xn != nil:
result.add xlHeader
result.add $$x.xn
if x.postProcess != ("", ""):
result = result.replace(x.postProcess[0], x.postProcess[1])
else:
result = x.raw
proc `$`*(x: XlWorkbook): string =
## Convert XlWorkbook object to string.
result = "XlWorkBook("
result.add "sheets: ["
for s in x.sheets:
result.addQuoted s.name
result.add ", "
result.removeSuffix(", ")
result.add "])"
proc `$`*(x: XlSheet): string =
## Convert XlSheet object to string.
result = "XlSheet("
result.add "name: "
result.addQuoted x.name
result.add ", count: "
result.addQuoted x.count
if not x.isEmpty:
result.add ", dimension: "
result.addQuoted (x.first, x.last).name
result.add ")"
proc `$`*(x: XlCell|XlRow|XlCol): string =
## Convert XlCell, XlRow, or XlCol object to string.
result = $x.type & "("
when x is XlCell:
result.add x.rc.name
elif x is XlRow:
result.add $(x.row + 1)
elif x is XlCol:
result.add (0, x.col).name
result.removeSuffix("1")
result.add ")"
proc `$`*(x: XlRange): string =
## Convert XlRange object to string.
result = "XlRange("
if not x.isEmpty:
result.add (x.first, x.last).name
result.add ")"
proc `$`*(x: XlCollection): string =
## Convert XlCollection object to string.
result = "XlCollection("
for rc in x.rcs.sortedItems:
result.add rc.name
result.add ","
result.removeSuffix(",")
result.add ")"
proc `$`*(x: XlNumFmt|XlColor|XlFont|XlAlignment|XlBorder|XlSide|XlFill|
XlPattern|XlProtection|XlSheetProtection): string =
## Convert style related object to string.
## The output can copy and paste as nim code.
result = $x.type & "("
for k, v in fieldPairs(x):
if v.isSome:
result.add k & ": "
result.addQuoted v.get
result.add ", "
result.removeSuffix(", ")
result.add ")"
proc `$`*(x: seq[Option[XlColor]]): string =
## Convert style related object to string.
## The output can copy and paste as nim code.
result.add "@["
for i in x:
if i.isSome:
result.add $i.get
result.add ", "
result.removeSuffix(", ")
result.add "]"
proc `$`*(x: XlGradient): string =
## Convert style related object to string.
## The output can copy and paste as nim code.
result = "XlGradient("
for k, v in fieldPairs(x):
when v is Option:
if v.isSome:
result.add k & ": "
result.addQuoted v.get
result.add ", "
elif v is seq:
result.add k & ": "
result.add $v
result.add ", "
result.removeSuffix(", ")
result.add ")"
proc `$`*(x: XlStyle|XlProperties): string =
## Convert style related object to string.
## The output can copy and paste as nim code.
result = $x.type & "("
for k, v in fieldPairs(x):
if v != default(v.type):
result.add k & ": "
result.addQuoted v
result.add ", "
result.removeSuffix(", ")
result.add ")"
proc `$`(x: openArray[XlRich]): string =
result = "{"
for rich in x:
result.addQuoted rich.text
result.add ": "
result.add $rich.font
result.add ", "
if x.len == 0:
result.add ":"
else:
result.removeSuffix(", ")
result.add "}"
proc `$`*(x: XlRiches): string =
## Convert XlRiches to string.
## The output can copy and paste as nim code.
result = $toOpenArray(x, 0, x.high)
proc `$`*[T](x: array[T, XlRich]): string =
## Convert XlRiches to string.
## The output can copy and paste as nim code.
result = $toOpenArray(x, 0, x.high)
proc isParsed(sheet: XlSheet): bool {.inline.} =
return not sheet.obj.xn.isNil
proc `{}`(xw: XlWorkbook, file: string): XlNode =
if file in xw.contents:
let obj = xw.contents[file]
obj.parse()
return obj.xn
else:
raise newException(XlError, file & " not found")
proc dup(cell: XlCell): XlCell =
result = XlCell()
result[] = cell[]
if result.change != nil: # change is ref, deep copy it
result.change = XlChange()
result.change[] = cell.change[]
template updateFirstLast(x: XlSheet|XlRange, rc: XlRC) =
x.first.row = min(x.first.row, rc.row)
x.first.col = min(x.first.col, rc.col)
x.last.row = max(x.last.row, rc.row)
x.last.col = max(x.last.col, rc.col)
proc update(xs: XlSheet, rc: XlRC) =
if xs.isEmpty:
xs.first = rc
xs.last = rc
else:
xs.updateFirstLast(rc)
proc update(xs: XlSheet, c: XlCell) =
let rc = c.rc
xs.update(rc)
xs.cells[rc] = c
proc update(xs: XlSheet) =
if xs.isEmpty:
xs.first = EmptyRowCol
xs.last = EmptyRowCol
else:
xs.first = (int.high, int.high)
xs.last = (int.low, int.low)
for rc in xs.cells.keys:
xs.updateFirstLast(rc)
template check(obj: untyped, field: untyped, error: bool, assertion: untyped) =
if obj.field.isSome:
var value {.inject.} = obj.field.get
if not assertion:
if error:
raise newException(XlError, "Invalid " & $obj)
else:
obj.field = none obj.field.get.type
template checkValidate(obj: untyped, field: untyped, error: bool) =
if obj.field.isSome:
validate(obj.field.get, error)
if obj.field.get == default(obj.field.get.type):
obj.field = none obj.field.get.type
proc validate(color: var XlColor, error: bool) =
check(color, rgb, error): value.len in {6, 8} and value.allCharsInSet(HexDigits)
check(color, theme, error): value >= 0
check(color, indexed, error): value in 0..64
check(color, tint, error): value in -1.0..1.0
proc validate(side: var XlSide, error: bool) =
check(side, style, error):
value in ["dashDot","dashDotDot", "dashed","dotted", "double", "hair",
"medium", "mediumDashDot", "mediumDashDotDot", "mediumDashed",
"slantDashDot", "thick", "thin"]
checkValidate(side, color, error)
proc validate(numFmt: var XlNumFmt, error: bool) =
check(numFmt, code, error): value != ""
proc validate(font: var XlFont, error: bool) =
check(font, charset, error): value >= 0
check(font, family, error): value in 0..14
check(font, size, error): value >= 0
check(font, underline, error):
value in ["", "single", "double", "singleAccounting", "doubleAccounting"]
check(font, vertAlign, error):
value in ["superscript", "subscript", "baseline"]
check(font, scheme, error):
value in ["major", "minor"]
checkValidate(font, color, error)
proc validate(gradient: var XlGradient, error: bool) =
check(gradient, gradientType, error):
value in ["linear", "path"]
for i in countdown(gradient.stops.high, 0):
validate(gradient.stops[i], error)
if gradient.stops[i] == default(XlColor):
gradient.stops.delete(i)
proc validate(pattern: var XlPattern, error: bool) =
check(pattern, patternType, error):
value in ["none", "solid", "mediumGray", "darkGray", "lightGray",
"darkHorizontal", "darkVertical", "darkDown", "darkUp", "darkGrid",
"darkTrellis", "lightHorizontal", "lightVertical", "lightDown",
"lightUp", "lightGrid", "lightTrellis", "gray125", "gray0625"]
checkValidate(pattern, fgColor, error)
checkValidate(pattern, bgColor, error)
proc validate(fill: var XlFill, error: bool) =
checkValidate(fill, patternFill, error)
checkValidate(fill, gradientFill, error)
proc validate(border: var XlBorder, error: bool) =
checkValidate(border, left, error)
checkValidate(border, right, error)
checkValidate(border, top, error)
checkValidate(border, bottom, error)
checkValidate(border, diagonal, error)
checkValidate(border, vertical, error)
checkValidate(border, horizontal, error)
proc validate(align: var XlAlignment, error: bool) =
check(align, horizontal, error):
value in ["general", "left", "center", "right", "fill", "justify",
"centerContinuous", "distributed"]
check(align, vertical, error):
value in ["top", "center", "bottom", "justify", "distributed"]
check(align, textRotation, error): value in -90..180 or value == 255
check(align, indent, error): value >= 0
check(align, relativeIndent, error): value >= 0
check(align, readingOrder, error): value >= 0
proc validate(align: var XlProtection, error: bool) {.inline.} =
# nothing to do for XlProtection
discard
proc option[T](x: XlNode, name: XlNsName): Option[T] {.inline.} =
let val = x[name]
if val == "":
return none T
try:
when T is string: result = some val
elif T is SomeInteger: result = some(T parseInt(val))
elif T is SomeFloat: result = some(T parseFloat(val))
elif T is bool: result = some(val == "true" or parseInt(val).bool)
else:
{.error: "unknow type " & $T.}
except:
return none T
proc childOption[T](x: XlNode, name: XlNsName, attr: XlNsName): Option[T] {.inline.} =
var child = x.child(name)
if child.isNil:
return none T
return option[T](child, attr)
proc parseColor(xColor: XlNode): XlColor =
result.`auto` = option[bool](xColor, NsMain\"auto")
result.rgb = option[string](xColor, NsMain\"rgb")
result.indexed = option[int](xColor, NsMain\"indexed")
result.theme = option[int](xColor, NsMain\"theme")
result.tint = option[float](xColor, NsMain\"tint")
validate(result, error=false)
proc newChildColor(x: XlNode, name: XlNsName, color: XlColor): XlNode =
result = newXlNode(x, name)
result["auto"] = color.`auto`
result["rgb"] = color.rgb
result["indexed"] = color.indexed
result["theme"] = color.theme
result["tint"] = color.tint
proc parseAlignment(xStyles: XlNode, style: int): XlAlignment =
if xStyles.hasChildN(NsMain\"cellXfs", style, xf) and
xf.hasChild(NsMain\"alignment", xAlign):
result.horizontal = option[string](xAlign, NsMain\"horizontal")
result.vertical = option[string](xAlign, NsMain\"vertical")
result.textRotation = option[int](xAlign, NsMain\"textRotation")
result.wrapText = option[bool](xAlign, NsMain\"wrapText")
result.shrinkToFit = option[bool](xAlign, NsMain\"shrinkToFit")
result.indent = option[int](xAlign, NsMain\"indent")
result.relativeIndent = option[int](xAlign, NsMain\"relativeIndent")
result.justifyLastLine = option[bool](xAlign, NsMain\"justifyLastLine")
result.readingOrder = option[int](xAlign, NsMain\"readingOrder")
if result.textRotation == 255:
result.verticalText = true
validate(result, error=false)
proc newChildAlignment(x: XlNode, name: XlNsName, align: XlAlignment): XlNode =
result = newXlNode(x, name)
result["horizontal"] = align.horizontal
result["vertical"] = align.vertical
result["wrapText"] = align.wrapText
result["shrinkToFit"] = align.shrinkToFit
result["indent"] = align.indent
result["relativeIndent"] = align.relativeIndent
result["justifyLastLine"] = align.justifyLastLine
result["readingOrder"] = align.readingOrder
if align.verticalText.isSome and align.verticalText.get:
result["textRotation"] = 255
elif align.textRotation.isSome:
if align.textRotation.get < 0: # -90 ~ -1 should be 180 ~ 91
result["textRotation"] = abs(align.textRotation.get) + 90
else:
result["textRotation"] = align.textRotation
proc parseProtection(xStyles: XlNode, style: int): XlProtection =
if xStyles.hasChildN(NsMain\"cellXfs", style, xf) and
xf.hasChild(NsMain\"protection", xProtection):
result.locked = option[bool](xProtection, NsMain\"locked")
result.hidden = option[bool](xProtection, NsMain\"hidden")
validate(result, error=false)
proc newChildProtection(x: XlNode, name: XlNsName, protection: XlProtection): XlNode =
result = newXlNode(x, name)
result["locked"] = protection.locked
result["hidden"] = protection.hidden
proc childColorOption(x: XlNode, name: XlNsName): Option[XlColor] =
var child = x.child(name)
if child.isNil:
return none XlColor
result = some parseColor(child)
proc childSideOption(x: XlNode, name: XlNsName): Option[XlSide] =
var child = x.child(name)
if child.isNil:
return none XlSide
var side = XlSide()
side.style = option[string](child, NsMain\"style")
side.color = childColorOption(child, NsMain\"color")
return if side == default(XlSide): none XlSide else: some side
proc addChildAttr[T](x: XlNode, name: XlNsName, attr: string, opt: Option[T]) =
if opt.isSome:
var child = x.addChildXlNode(name)
if attr != "":
child[attr] = opt
proc addChildColor(x: XlNode, name: XlNsName, color: Option[XlColor]) =
if color.isSome:
x.add x.newChildColor(name, color.get)
proc addChildSide(x: XlNode, name: XlNsName, side: Option[XlSide]) =
if side.isSome:
var xSide = x.addChildXlNode(name)
var side = side.get
xSide["style"] = side.style
xSide.addChildColor(NsMain\"color", side.color)