-
Notifications
You must be signed in to change notification settings - Fork 1
/
tabxlsx.py
executable file
·1585 lines (1551 loc) · 69.9 KB
/
tabxlsx.py
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
#! /usr/bin/env python3
"""
TabXLSX reads and writes Excel xlsx files. It does not depend on other libraries.
The output can be piped as a markdown table or csv-like data as well. A number
of output format options are available but less than the tabtotext.py module.
If the input contains only one table then it is used, otherwise specify which should be printed."""
__copyright__ = "(C) 2023-2024 Guido Draheim, licensed under the Apache License 2.0"""
__version__ = "1.6.3365"
from typing import Union, List, Dict, cast, Tuple, Optional, TextIO, Iterable, NamedTuple, Mapping, TypeVar, Generic, Iterator
from collections import OrderedDict
from datetime import date as Date
from datetime import datetime as Time
from datetime import timedelta as Plus
from datetime import timezone as TimeZone
from io import StringIO, TextIOWrapper
from zipfile import ZipFile, ZIP_DEFLATED
from xml.etree import ElementTree as ET
import os.path as fs
import os
import re
import sys
# The functions in this script mimic those of openpyxl - we only implement what we need for tabtoxlsx
# (actually, we make an export with openpyxl and then we adapt the code here to generate the same bytes)
# from openpyxl import Workbook, load_workbook
# from openpyxl.worksheet.worksheet import Worksheet
# from openpyxl.styles.cell_style import CellStyle as Style
# from openpyxl.styles.alignment import Alignment
# from openpyxl.utils import get_column_letter
# (have a look at 'make_workbook' for the generation part)
from logging import getLogger, basicConfig, ERROR
logg = getLogger("TABXLSX")
SECTION = "data"
DATEFMT = "%Y-%m-%d"
TIMEFMT = "%Y-%m-%d.%H%M"
FLOATFMT = "%4.2f"
MINWIDTH = 5
MAXCOL = 1000
MAXROWS = 100000
NIX = ""
def get_column_letter(num: int) -> str:
return chr(ord('A') + (num - 1))
class Alignment:
horizontal: str
def __init__(self, *, horizontal: str = NIX) -> None:
self.horizontal = horizontal
class CellStyle:
alignment: Alignment
number_format: str
protection: str
def __init__(self, *, number_format: str = NIX, protection: str = NIX) -> None:
self.alignment = Alignment()
self.number_format = number_format
self.protection = protection
CellValue = Union[None, bool, int, float, str, Time, Date]
class Cell:
value: CellValue
data_type: str
alignment: Optional[Alignment]
number_format: Optional[str]
protection: Optional[str]
_xf: int
_numFmt: int
def __init__(self) -> None:
self.value = None
self.data_type = NIX
self.alignment = None
self.number_format = None
self.protection = None
self._xf = 0
self._numFmt = 0
def __str__(self) -> str:
return str(self.value)
def __repr__(self) -> str:
return str(self.value)
class Dimension:
width: int
def __init__(self, *, width: int = 8) -> None:
self.width = width
class DimensionsHolder:
columns: Dict[str, Dimension]
def __init__(self) -> None:
self.columns = {}
def __getitem__(self, column: str) -> Dimension:
if column not in self.columns:
self.columns[column] = Dimension()
return self.columns[column]
class Worksheet:
rows: List[Dict[str, Cell]]
title: str
column_dimensions: DimensionsHolder
_mindim: str
_maxdim: str
def __init__(self, title: str = NIX) -> None:
self.title = title
self.rows = []
self.column_dimensions = DimensionsHolder()
def cell(self, row: int, column: int) -> Cell:
atrow = row - 1
name = get_column_letter(column) + str(row)
while atrow >= len(self.rows):
self.rows.append({})
if name not in self.rows[atrow]:
self.rows[atrow][name] = Cell()
return self.rows[atrow][name]
def __getitem__(self, name: str) -> Cell:
m = re.match("([A-Z]+)([0-9]+)", name)
if not m:
logg.error("can not check %s", name)
raise ValueError(name)
atrow = int(m.group(2)) - 1
while atrow >= len(self.rows):
self.rows.append({})
if name not in self.rows[atrow]:
self.rows[atrow][name] = Cell()
return self.rows[atrow][name]
class Workbook:
_sheets: List[Worksheet]
_active_sheet_index: int
def __init__(self) -> None:
self._sheets = [Worksheet()]
self._active_sheet_index = 0
@property
def worksheets(self) -> List[Worksheet]:
return self._sheets
@property
def active(self) -> Worksheet:
return self._sheets[self._active_sheet_index]
def save(self, filename: str) -> None:
save_workbook(filename, self)
def create_sheet(self) -> Worksheet: # pragma: no cover
ws = Worksheet()
self._active_sheet_index = len(self._sheets)
self._sheets.append(ws)
return ws
def get_sheet_names(self) -> List[str]: # pragma: no cover
names: List[str] = []
for ws in self._sheets:
names += [ws.title]
return names
def get_sheet_by_name(self, name: str) -> Worksheet: # pragma: no cover
for ws in self._sheets:
if name == ws.title:
return ws
raise KeyError("Worksheet does not exist")
def __getitem__(self, key: str) -> Worksheet: # pragma: no cover
return self.get_sheet_by_name(key)
@property
def sheetnames(self) -> List[str]: # pragma: no cover
return self.get_sheet_names()
def save_workbook(filename: str, workbook: Workbook) -> None:
xmlns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns_r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns_p = "http://schemas.openxmlformats.org/package/2006/relationships"
xmlns_w = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
xmlns_s = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
xmlns_t = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"
xmlns_c = "http://schemas.openxmlformats.org/package/2006/content-types"
NUMFMT = 164
numFmts: List[str] = ["yyyy-mm-dd h:mm:ss"]
for sheet in workbook.worksheets:
sheet._mindim = ""
sheet._maxdim = ""
for row in sheet.rows:
for cellname, cell in row.items():
if not sheet._mindim:
sheet._mindim = cellname
sheet._maxdim = cellname
if cellname < sheet._mindim:
sheet._mindim = cellname
if cellname > sheet._maxdim:
sheet._maxdim = cellname
if cell.number_format:
if cell.number_format in ["General"]:
continue
if cell.number_format not in numFmts:
numFmts.append(cell.number_format)
cell._numFmt = NUMFMT + numFmts.index(cell.number_format)
cellXfs: List[str] = []
for sheet in workbook.worksheets:
for row in sheet.rows:
for cell in row.values():
numFmtId = cell._numFmt
applyAlignment = 0
xml_alignment = ""
if cell.alignment and cell.alignment.horizontal:
applyAlignment = 1
horizontal = cell.alignment.horizontal
xml_alignment = F'<alignment horizontal="{horizontal}"/>'
xml_xf = F'<xf'
xml_xf += F' numFmtId="{numFmtId}"'
xml_xf += F' fontId="0"'
xml_xf += F' fillId="0"'
xml_xf += F' borderId="0"'
xml_xf += F' applyAlignment="{applyAlignment}"'
xml_xf += F' pivotButton="0"'
xml_xf += F' quotePrefix="0"'
xml_xf += F' xfId="0"'
xml_xf += '>'
xml_xf += xml_alignment
xml_xf += F'</xf>'
if xml_xf not in cellXfs:
cellXfs.append(xml_xf)
cell._xf = cellXfs.index(xml_xf) + 1
style_xml = F'<styleSheet xmlns="{xmlns}">'
style_xml += F'<numFmts count="{len(numFmts)}">'
for num, fmtCode in enumerate(numFmts):
numFmtId = NUMFMT + num
style_xml += F'<numFmt numFmtId="{numFmtId}" formatCode="{fmtCode}"/>'
style_xml += F'</numFmts>'
style_xml += F'<fonts count="1"><font><name val="Calibri"/>'
style_xml += F'<family val="2"/><color theme="1"/><sz val="11"/>'
style_xml += F'<scheme val="minor"/></font></fonts>'
# style_xml += f'<fills count="1" /><fill><patternFill/></fill></fills>'
style_xml += f'<fills count="2"><fill><patternFill/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
style_xml += F'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
style_xml += F'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
style_xml += F'<cellXfs count="{len(cellXfs)+1}">'
style_xml += F'<xf numFmtId="0" fontId="0" fillId="0" borderId="0" pivotButton="0" quotePrefix="0" xfId="0"/>'
for xf in cellXfs:
style_xml += xf
style_xml += F'</cellXfs>'
style_xml += F'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0" hidden="0"/></cellStyles>'
style_xml += F'<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/>'
style_xml += F'</styleSheet>'
workbook_xml = F'<workbook xmlns="{xmlns}">'
workbook_xml += F'<workbookPr/>'
workbook_xml += F'<workbookProtection/>'
# workbook_xml += F'<bookViews/>'
workbook_xml += F'<bookViews><workbookView visibility="visible" minimized="0" showHorizontalScroll="1" showVerticalScroll="1" showSheetTabs="1" tabRatio="600" firstSheet="0" activeTab="0" autoFilterDateGrouping="1"/></bookViews>'
workbook_xml += F'<sheets>'
worksheets: List[str] = []
for sheet in workbook.worksheets:
wxml = F'<worksheet xmlns="{xmlns}">'
wxml += '<sheetPr><outlinePr summaryBelow="1" summaryRight="1"/><pageSetUpPr/></sheetPr>'
wxml += F'<dimension ref="{sheet._mindim}:{sheet._maxdim}"/>'
wxml += '<sheetViews><sheetView workbookViewId="0"><selection activeCell="A1" sqref="A1"/></sheetView></sheetViews>'
wxml += '<sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>'
if sheet.column_dimensions.columns:
wxml += F'<cols>'
for nam, col in sheet.column_dimensions.columns.items():
wxml += F'<col width="{col.width}" customWidth="1" min="1" max="1"/>'
wxml += F'</cols>'
wxml += F'<sheetData>'
for num, row in enumerate(sheet.rows):
if not row: continue # empty
wxml += F'<row r="{num+1}">'
for r, cell in row.items():
if cell.value is None:
continue
elif isinstance(cell.value, str):
if cell.data_type in ["", "f"] and cell.value.startswith("="):
s = cell._xf
f = cell.value[1:]
wxml += F'<c r="{r}" s="{s}">'
wxml += F'<f>{f}</f>'
wxml += F'</c>'
else:
s = cell._xf
t = "inlineStr"
wxml += F'<c r="{r}" s="{s}" t="{t}">'
wxml += F'<is><t>{cell.value}</t></is>'
wxml += F'</c>'
else:
value: Union[int, float]
t = "n"
if isinstance(cell.value, bool):
value = 1 if cell.value else 0
t = 'b'
elif isinstance(cell.value, Time):
value = cell.value.toordinal() - 693594.
seconds = cell.value.hour * 3600 + cell.value.minute * 60 + cell.value.second
value += seconds / 86400.
elif isinstance(cell.value, Date):
value = cell.value.toordinal() - 693594.
else:
value = cell.value
s = cell._xf
# wxml += F'<c r="{r}" s="{s}">'
wxml += F'<c r="{r}" s="{s}" t="{t}">'
wxml += F'<v>{value}</v>'
wxml += F'</c>'
wxml += F'</row>'
wxml += F'</sheetData>'
wxml += F'<pageMargins left="0.75" right="0.75" top="1" bottom="1" header="0.5" footer="0.5"/>'
wxml += F'</worksheet>'
worksheets.append(wxml)
workbook_xml += F'<sheet xmlns:r="{xmlns_r}" name="{sheet.title}"'
workbook_xml += F' sheetId="{len(worksheets)}"'
workbook_xml += F' state="visible"'
workbook_xml += F' r:id="rId{len(worksheets)}"/>'
workbook_xml += F'</sheets>'
workbook_xml += F'<definedNames/><calcPr calcId="124519" fullCalcOnLoad="1"/>'
workbook_xml += F'</workbook>'
theme_xml = F'<?xml version="1.0"?>' + "\n"
theme_xml = F'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">'
theme_xml = F'<a:themeElements/><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>'
with ZipFile(filename, "w", compression=ZIP_DEFLATED) as zipfile:
worksheetfilelist = []
rels_xml = F'<Relationships xmlns="{xmlns_p}">'
for num, xml in enumerate(worksheets):
worksheetfile = F'worksheets/sheet{num+1}.xml'
worksheet_Id = F'rId{num+1}'
rels_xml += F'<Relationship Type="{xmlns_w}"'
rels_xml += F' Target="/xl/{worksheetfile}" Id="{worksheet_Id}"/>'
with zipfile.open("xl/" + worksheetfile, "w") as xmlfile:
xmlfile.write(xml.encode('utf-8'))
worksheetfilelist += [worksheetfile]
stylefile = F"styles.xml"
style_Id = F'rId{len(worksheets)+1}'
rels_xml += F'<Relationship Type="{xmlns_s}"'
rels_xml += F' Target="{stylefile}" Id="{style_Id}"/>'
with zipfile.open("xl/" + stylefile, "w") as xmlfile:
xmlfile.write(style_xml.encode('utf-8'))
themefile = F"theme/theme1.xml"
theme_Id = F'rId{len(worksheets)+2}'
rels_xml += F'<Relationship Type="{xmlns_t}"'
rels_xml += F' Target="{themefile}" Id="{theme_Id}"/>'
with zipfile.open("xl/" + themefile, "w") as xmlfile:
xmlfile.write(theme_xml.encode('utf-8'))
rels_xml += F'</Relationships>'
workbookfile = "workbook.xml"
with zipfile.open("xl/" + workbookfile, "w") as xmlfile:
xmlfile.write(workbook_xml.encode('utf-8'))
relsfile = "_rels/workbook.xml.rels"
with zipfile.open("xl/" + relsfile, "w") as xmlfile:
xmlfile.write(rels_xml.encode('utf-8'))
apps_xml = F'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"><Application>Microsoft Excel</Application><AppVersion>3.0</AppVersion></Properties>'
appsfile = "docProps/app.xml"
core_xml = F'<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">openpyxl</dc:creator><dcterms:created xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dcterms:W3CDTF">2024-07-09T21:58:37Z</dcterms:created><dcterms:modified xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="dcterms:W3CDTF">2024-07-09T21:58:37Z</dcterms:modified></cp:coreProperties>'
corefile = "docProps/core.xml"
with zipfile.open(appsfile, "w") as xmlfile:
xmlfile.write(apps_xml.encode('utf-8'))
with zipfile.open(corefile, "w") as xmlfile:
xmlfile.write(core_xml.encode('utf-8'))
init_xml = F'<Relationships xmlns="{xmlns_p}">'
init_xml += F'<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/{workbookfile}" Id="rId1"/>'
init_xml += F'<Relationship Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml" Id="rId2"/>'
init_xml += F'<Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml" Id="rId3"/>'
init_xml += F'</Relationships>'
initfile = "_rels/.rels"
with zipfile.open(initfile, "w") as xmlfile:
xmlfile.write(init_xml.encode('utf-8'))
content_xml = F'<Types xmlns="{xmlns_c}">'
content_xml += '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
content_xml += '<Default Extension="xml" ContentType="application/xml"/>'
content_xml += '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
content_xml += '<Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>'
content_xml += '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>'
content_xml += '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>'
# content_xml += '<Default Extension="xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
for worksheetfile in worksheetfilelist:
content_xml += F'<Override PartName="/xl/{worksheetfile}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
content_xml += '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
content_xml += '</Types>'
contentfile = "[Content_Types].xml"
with zipfile.open(contentfile, "w") as xmlfile:
xmlfile.write(content_xml.encode('utf-8'))
_dateformats = ['d.mm.yy', 'yyyy-mm-dd']
_timeformats = ['yyyy-mm-dd hh:mm', 'yyyy-mm-dd h:mm:ss']
def load_workbook(filename: str) -> Workbook:
workbook = Workbook()
ws = workbook.active
with ZipFile(filename) as zipfile:
sharedStrings: List[str] = []
try:
with zipfile.open("xl/sharedStrings.xml") as xmlfile:
xml = ET.parse(xmlfile)
for item in xml.getroot():
if ("}" + item.tag).endswith("}si"):
text = ""
for block in item:
if ("}" + block.tag).endswith("}t"):
text += block.text or ""
sharedStrings += [text]
except KeyError as e:
logg.debug("do not use sharedStrings.xml: %s", e)
formatcodes: Dict[str, str] = {}
numberformat: Dict[str, str] = {}
with zipfile.open("xl/styles.xml") as xmlfile:
xml = ET.parse(xmlfile)
for item in xml.getroot():
if ("}" + item.tag).endswith("numFmts"):
for fmt in item:
numFmtId = fmt.get("numFmtId", "?")
formatcode = fmt.get("formatCode", "?")
logg.debug("numFmtId %s formatCode %s", numFmtId, formatcode)
formatcodes[numFmtId] = formatcode
if ("}" + item.tag).endswith("cellXfs"):
style = 0
for xfs in item:
numFmtId = xfs.get("numFmtId", "?")
logg.debug("numFmtId %s", numFmtId)
if numFmtId in formatcodes:
numberformat[str(style)] = formatcodes[numFmtId]
style += 1
sheetnames: Dict[str, str] = {}
with zipfile.open("xl/workbook.xml") as xmlfile:
xml = ET.parse(xmlfile)
for item in xml.getroot():
if ("}" + item.tag).endswith("}sheets"):
for sheet in item:
sheetname = sheet.get("name", "")
sheetId = sheet.get("sheetId", "")
if sheetId and sheetname:
sheetnames[sheetId] = sheetname
namelist = zipfile.namelist()
for sheetnumber in range(1, 99):
sheetId = str(sheetnumber)
sheetfilename = F"xl/worksheets/sheet{sheetId}.xml"
if sheetnumber > 1:
if sheetfilename not in namelist:
break
ws = Worksheet()
workbook._sheets.append(ws)
if sheetId in sheetnames:
ws.title = sheetnames[sheetId]
with zipfile.open(sheetfilename) as xmlfile:
logg.debug("load %s:%s", filename, sheetfilename)
xml = ET.parse(xmlfile)
for item in xml.getroot():
if ("}" + item.tag).endswith("}sheetData"):
for rowdata in item:
row = int(rowdata.get("row", "0"))
for cell in rowdata:
value: CellValue = None
t = cell.get("t", "n")
s = cell.get("s", "0")
r = cell.get("r")
v = ""
x = ""
for data in cell:
if ("}" + data.tag).endswith("}v"):
v = data.text or ""
elif ("}" + data.tag).endswith("}is"):
for block in data:
x += block.text or ""
elif ("}" + data.tag).endswith("}f"):
x = "=" + (data.text or "")
t = "f"
logg.debug("r = %s | s = %s | t =%s | v = %s| x = %s", r, s, t, v, x)
if t in ["b"]:
value = True if v == "1" else False
elif t in ["f", "inlineStr", ]:
value = x
elif t in ["s"]:
value = sharedStrings[int(v)]
# elif v in [""]:
# value = ""
else:
if "." not in v:
value = int(v)
value1 = float(value)
else:
value1 = float(v)
value = value1
if s in numberformat:
numfmt = numberformat[s]
logg.debug("value %s numberformat %s", value, numfmt)
if numfmt in _timeformats:
value0 = int(value1)
value2 = Time.fromordinal(value0 + 693594)
value3 = int(((value1 - value0) * 86400) + 0.4)
value = value2 + Plus(seconds=value3)
t = "d"
elif numfmt in _dateformats:
value0 = int(value1)
value2 = Time.fromordinal(value0 + 693594)
value = value2.date()
t = "d"
else:
logg.debug("%s no datetime format", s)
else:
logg.debug("%s has no numbeformt", s)
if r:
ws[r].value = value
ws[r].data_type = t
return workbook
# .....................................................................
# Files can contain multiple tables which get represented as a list of sheets where
# each sheet remembers the title and the order columns in the original table. This allows
# to convert file formats with the order of tables, columns (and rows) being preserved.
class TabSheet(NamedTuple):
data: List[Dict[str, CellValue]]
headers: List[str]
title: str
def tablistfor(tabdata: Dict[str, List[Dict[str, CellValue]]]) -> List[TabSheet]:
tablist: List[TabSheet] = []
for name, data in tabdata.items():
tablist += [TabSheet(data, [], name)]
return tablist
def tablistitems(tablist: List[TabSheet]) -> Iterator[Tuple[str, List[Dict[str, CellValue]]]]:
for tabsheet in tablist:
yield tabsheet.title, tabsheet.data
def tablistmap(tablist: List[TabSheet]) -> Dict[str, List[Dict[str, CellValue]]]:
tabdata: Dict[str, List[Dict[str, CellValue]]] = OrderedDict()
for name, data in tablistitems(tablist):
tabdata[name] = data
return tabdata
def tablistfileXLSX(filename: str) -> List[TabSheet]:
workbook = load_workbook(filename)
return tablist_workbook(workbook)
def tablist_workbook(workbook: Workbook, section: str = NIX) -> List[TabSheet]:
tab = []
for ws in workbook.worksheets:
title = ws.title
cols: List[str] = []
for col in range(MAXCOL):
header = ws.cell(row=1, column=col + 1)
if header.value is None:
break
name = header.value
if name is None:
break
cols.append(str(name))
logg.debug("xlsx found %s cols\n\t%s", len(cols), cols)
data: List[Dict[str, CellValue]] = []
for atrow in range(MAXROWS):
record = []
found = 0
for atcol in range(len(cols)):
cell = ws.cell(row=atrow + 2, column=atcol + 1)
if cell.data_type in ["f"]:
continue
value = cell.value
# logg.debug("[%i,%si] cell.value = %s", atcol, atrow, value)
if value is not None:
found += 1
if isinstance(value, str) and value == " ":
value = ""
record.append(value)
if not found:
break
newrow = dict(zip(cols, record))
data.append(newrow) # type: ignore[arg-type]
tab.append(TabSheet(data, cols, title))
return tab
def currency() -> str:
""" make dependent on locale ? """
currency_dollar = 0x024
currency_pound = 0x0A3
currency_symbol = 0x0A4 # in iso-8859-1 it shows the euro sign
currency_yen = 0x0A5
currency_euro = 0x20AC
return chr(currency_euro)
def tablistmake_workbook(tablist: List[TabSheet], selected: List[str] = [], minwidth: int = 0) -> Optional[Workbook]:
workbook: Optional[Workbook] = None
for tabsheet in tablist:
if workbook is not None:
workbook.create_sheet()
work = tabto_workbook(tabsheet.data, tabsheet.headers, selected,
minwidth=minwidth, section=tabsheet.title,
workbook=workbook)
if workbook is None:
workbook = work
return workbook
def tabtoXLSX(filename: str, data: Iterable[Dict[str, CellValue]], headers: List[str] = [], selected: List[str] = [], minwidth: int = 0, section: str = NIX) -> str:
workbook = tabto_workbook(data, headers, selected, minwidth, section)
save_workbook(filename, workbook)
return "TABXLSX"
def tabto_workbook(data: Iterable[Dict[str, CellValue]], headers: List[str] = [], selected: List[str] = [], minwidth: int = 0,
section: str = NIX, workbook: Optional[Workbook] = None) -> Workbook:
minwidth = minwidth or MINWIDTH
logg.debug("tabtoXLSX:")
renameheaders: Dict[str, str] = {}
showheaders: List[str] = []
sortheaders: List[str] = []
formats: Dict[str, str] = {}
combine: Dict[str, List[str]] = {}
for header in headers:
combines = ""
for selheader in header.split("|"):
if "@" in selheader:
selcol, rename = selheader.split("@", 1)
else:
selcol, rename = selheader, ""
if ":" in selcol:
name, form = selcol.split(":", 1)
if isinstance(formats, dict):
fmts = form if "{" in form else ("{:" + form + "}")
formats[name] = fmts.replace("i}", "n}").replace("u}", "n}").replace("r}", "s}").replace("a}", "s}")
else:
name = selcol
showheaders += [name] # headers make a default column order
if rename:
sortheaders += [name] # headers does not sort anymore
if not combines:
combines = name
elif combines not in combine:
combine[combines] = [name]
elif name not in combine[combines]:
combine[combines] += [name]
if rename:
renameheaders[name] = rename
logg.debug("renameheaders = %s", renameheaders)
logg.debug("sortheaders = %s", sortheaders)
logg.debug("formats = %s", formats)
logg.debug("combine = %s", combine)
combined: Dict[str, List[str]] = {}
renaming: Dict[str, str] = {}
selcols: List[str] = []
for selecheader in selected:
combines = ""
for selec in selecheader.split("|"):
if "@" in selec:
selcol, rename = selec.split("@", 1)
else:
selcol, rename = selec, ""
if ":" in selcol:
name, form = selcol.split(":", 1)
if isinstance(formats, dict):
fmts = form if "{" in form else ("{:" + form + "}")
formats[name] = fmts.replace("i}", "n}").replace("u}", "n}").replace("r}", "s}").replace("a}", "s}")
else:
name = selcol
selcols.append(name)
if rename:
renaming[name] = rename
if not combines:
combines = name
elif combines not in combined:
combined[combines] = [name]
elif combines not in combined[combines]:
combined[combines] += [name]
logg.debug("combined = %s", combined)
logg.debug("renaming = %s", renaming)
logg.debug("selcols = %s", selcols)
if not selected:
combined = combine # argument
renaming = renameheaders
logg.debug("combined : %s", combined)
logg.debug("renaming : %s", renaming)
newsorts: Dict[str, str] = {}
colnames: Dict[str, str] = {}
for name, rename in renaming.items():
if "@" in rename:
newname, newsort = rename.split("@", 1)
elif rename and rename[0].isalpha():
newname, newsort = rename, ""
else:
newname, newsort = "", rename
if newname:
colnames[name] = newname
if newsort:
newsorts[name] = newsort
logg.debug("newsorts = %s", newsorts)
logg.debug("colnames = %s", colnames)
sortcolumns = [(name if name not in colnames else colnames[name]) for name in (selcols or sortheaders)]
if newsorts:
for num, name in enumerate(sortcolumns):
if name not in newsorts:
newsorts[name] = ("@" * len(str(num)) + str(num))
sortcolumns = sorted(newsorts, key=lambda x: newsorts[x])
logg.debug("sortcolumns : %s", sortcolumns)
if selcols:
selheaders = [(name if name not in colnames else colnames[name]) for name in (selcols)]
else:
selheaders = [(name if name not in colnames else colnames[name]) for name in (showheaders)]
def strNone(value: CellValue) -> str:
if isinstance(value, Time):
return value.strftime(TIMEFMT)
if isinstance(value, Date):
return value.strftime(DATEFMT)
return str(value)
def sortkey(header: str) -> str:
if header in selheaders:
num = selheaders.index(header)
return ("@" * len(str(num)) + str(num))
return header
def sortrow(row: Dict[str, CellValue]) -> str:
def asdict(item: Dict[str, CellValue]) -> Dict[str, CellValue]:
if hasattr(item, "_asdict"):
return item._asdict() # type: ignore[union-attr, no-any-return, arg-type, attr-defined]
return item
item = asdict(row)
sorts = sortcolumns
if sorts:
# numbers before empty before strings
sortvalue = ""
for sort in sorts:
if sort in item:
value = item[sort]
if value is None:
sortvalue += "\n?"
elif value is False:
sortvalue += "\n"
elif value is True:
sortvalue += "\n!"
elif isinstance(value, int):
val = "%i" % value
sortvalue += "\n" + (":" * len(val)) + val
elif isinstance(value, float):
val = "%.6f" % value
sortvalue += "\n" + (":" * val.index(".")) + val
elif isinstance(value, Time):
sortvalue += "\n" + value.strftime("%Y%m%d.%H%MS")
elif isinstance(value, Date):
sortvalue += "\n" + value.strftime("%Y%m%d")
else:
sortvalue += "\n" + str(value)
else:
sortvalue += "\n?"
return sortvalue
return ""
rows: List[Dict[str, CellValue]] = []
cols: Dict[str, int] = {}
for num, item in enumerate(data):
row: Dict[str, CellValue] = {}
if "#" in headers:
item["#"] = num + 1
cols["#"] = len(str(num + 1))
for name, value in item.items():
selname = name
if name in renameheaders and renameheaders[name] in selcols:
selname = renameheaders[name]
if selcols and selname not in selcols and "*" not in selcols:
continue
colname = selname if selname not in colnames else colnames[selname]
row[colname] = value # do not format the value here!
oldlen = cols[colname] if colname in cols else max(minwidth, len(colname))
cols[colname] = max(oldlen, len(strNone(value)))
rows.append(row)
sortedrows = list(sorted(rows, key=sortrow))
sortedcols = list(sorted(cols.keys(), key=sortkey))
return make_workbook(sortedrows, sortedcols, cols, formats, section=section, workbook=workbook)
def make_workbook(rows: List[Dict[str, CellValue]],
cols: List[str], colwidth: Dict[str, int], formats: Dict[str, str],
section: str = NIX, workbook: Optional[Workbook] = None) -> Workbook:
row = 0
workbook = workbook or Workbook()
ws = workbook.active
ws.title = section or SECTION
col = 0
for name in cols:
ws.cell(row=1, column=col + 1).value = name
ws.cell(row=1, column=col + 1).alignment = Alignment(horizontal="right")
if name in colwidth:
ws.column_dimensions[get_column_letter(col + 1)].width = colwidth[name]
col += 1
for item in rows:
row += 1
values: Dict[str, CellValue] = dict([(name, "") for name in cols])
for name, value in item.items():
values[name] = value
col = 0
for name in cols:
value = values[name]
at = {"column": col + 1, "row": row + 1}
if value is None:
ws.cell(**at).value = ""
ws.cell(**at).alignment = Alignment(horizontal="left")
ws.cell(**at).number_format = "General"
elif isinstance(value, Time):
ws.cell(**at).value = value
ws.cell(**at).alignment = Alignment(horizontal="right")
ws.cell(**at).number_format = "yyyy-mm-dd hh:mm"
elif isinstance(value, Date):
ws.cell(**at).value = value
ws.cell(**at).alignment = Alignment(horizontal="right")
ws.cell(**at).number_format = "yyyy-mm-dd"
elif isinstance(value, int):
ws.cell(**at).value = value
ws.cell(**at).alignment = Alignment(horizontal="right")
ws.cell(**at).number_format = "#,##0"
elif isinstance(value, float):
ws.cell(**at).value = value
ws.cell(**at).alignment = Alignment(horizontal="right")
ws.cell(**at).number_format = "#,##0.00"
if name in formats and "$}" in formats[name]:
ws.cell(**at).number_format = "#,##0.00" + currency()
else:
ws.cell(**at).value = value
ws.cell(**at).alignment = Alignment(horizontal="left")
ws.cell(**at).number_format = "General"
col += 1
return workbook
# ...........................................................
def sec_usec(sec: Optional[str]) -> Tuple[int, int]:
""" split float value to seconds and microsecond integers"""
if not sec:
return 0, 0
if "." in sec:
x = float(sec)
s = int(x)
u = int((x - s) * 1000000)
return s, u
return int(sec), 0
class StrToDate:
""" parsing iso8601 day formats"""
def __init__(self, datedelim: str = "-") -> None:
self.delim = datedelim
self.is_date = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)[.]?$".replace('-', datedelim))
self.is_part = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)[^\d].*".replace('-', datedelim))
def date(self, value: str) -> Optional[Date]:
got = self.is_date.match(value)
if got:
y, m, d = got.group(1), got.group(2), got.group(3)
return Date(int(y), int(m), int(d))
return None
def datepart(self, value: str) -> Optional[Date]:
got = self.is_part.match(value)
if got:
y, m, d = got.group(1), got.group(2), got.group(3)
return Date(int(y), int(m), int(d))
return None
def __call__(self, value: str) -> Union[str, Date, Time]:
d = self.date(value)
if d: return d
p = self.datepart(value)
if p: return p
return value
class StrToTime(StrToDate):
""" parsing iso8601 day or day-and-time formats with zone offsets"""
def __init__(self, datedelim: str = "-") -> None:
StrToDate.__init__(self, datedelim)
self.is_localtime = re.compile(
r"(\d\d\d\d)-(\d\d)-(\d\d)[.T ](\d\d)[:]?(\d\d)(?:[:](\d\d(?:[.]\d*)?))?$".replace('-', datedelim))
self.is_zonetime = re.compile(
r"(\d\d\d\d)-(\d\d)-(\d\d)[.T ](\d\d)[:]?(\d\d)(?:[:](\d\d(?:[.]\d*)?))?[ ]*(Z|UTC|[+-][0-9][0-9])(?:[:]?([0-9][0-9]))?$".replace('-', datedelim))
def time(self, value: str) -> Optional[Time]:
got = self.is_localtime.match(value)
if got:
y, m, d, H, M, S = got.group(1), got.group(2), got.group(3), got.group(4), got.group(5), got.group(6)
return Time(int(y), int(m), int(d), int(H), int(M), *sec_usec(S))
got = self.is_zonetime.match(value)
if got:
hh, mm = got.group(7), got.group(8)
if hh in ["Z", "UTC"]:
plus = TimeZone.utc
else:
plus = TimeZone(Plus(hours=int(hh), minutes=int(mm or 0)))
y, m, d, H, M, S = got.group(1), got.group(2), got.group(3), got.group(4), got.group(5), got.group(6)
return Time(int(y), int(m), int(d), int(H), int(M), *sec_usec(S), tzinfo=plus)
return None
def __call__(self, value: str) -> Union[str, Date, Time]:
d = self.date(value)
if d: return d
t = self.time(value)
if t: return t
return value
_atformats = ["@json", "@jsn", "@markdown", "@md", "@md2", "@md3", "@md4", "@md5", "@md6",
"@wide", "@read", "@txt", "@text",
"@tabs", "@tab", "@data", "@ifs", "@dat", "@csv", "@scsv", "@xls", "@xlsx"]
def fmt_selected(selected: List[str]) -> str:
for sel in selected:
if sel in _atformats:
return sel[1:]
return NIX
def tabtotext(data: Iterable[Dict[str, CellValue]], # ..
headers: List[str] = [], selected: List[str] = [],
*, fmt: str = "", tab: Optional[str] = None, padding: Optional[str] = None, minwidth: int = 0, section: str = NIX,
noheaders: bool = False, unique: bool = False, defaultformat: str = "") -> str:
stream = StringIO()
print_tabtotext(stream, data, headers, selected, # ..
tab=tab, padding=padding,
minwidth=minwidth, section=section,
noheaders=noheaders, unique=unique, defaultformat=(fmt or defaultformat))
return stream.getvalue()
def print_tabtotext(output: Union[TextIO, str], data: Iterable[Dict[str, CellValue]], # ..
headers: List[str] = [], selected: List[str] = [],
*, tab: Optional[str] = None, padding: Optional[str] = None, minwidth: int = 0, section: str = NIX,
noheaders: bool = False, unique: bool = False, defaultformat: str = "") -> str:
""" This code is supposed to be copy-n-paste into other files. You can safely try-import from
tabtotext or tabtoxlsx to override this function. Only a subset of features is supported. """
spec: Dict[str, str] = dict(cast(Tuple[str, str], (x, "") if "=" not in x else x.split("=", 1))
for x in selected if x.startswith("@"))
selected_fmt = fmt_selected(selected)
selected = [x for x in selected if not x.startswith("@")]
minwidth = minwidth or MINWIDTH
padding = " " if padding is None else padding
tab = "|" if tab is None else tab
def extension(filename: str) -> Optional[str]:
_, ext = fs.splitext(filename.lower())
if ext: return ext[1:]
return None
#
if isinstance(output, TextIO) or isinstance(output, StringIO):
out = output
fmt = defaultformat or selected_fmt
done = "stream"
elif "." in output:
fmt = extension(output) or defaultformat
if fmt in ["xls", "xlsx"]:
tabtoXLSX(output, data, headers, selected, section=section)
return "XLSX"
out = open(output, "wt", encoding="utf-8")
done = output
else:
fmt = output or defaultformat or selected_fmt
out = sys.stdout
done = output
#
if fmt in ["md", "markdown"]:
fmt = "GFM" # nopep8
if fmt in ["md2"]:
fmt = "GFM"
minwidth = 2 # nopep8
if fmt in ["md3"]:
fmt = "GFM"
minwidth = 3 # nopep8
if fmt in ["md4"]:
fmt = "GFM"
minwidth = 4 # nopep8
if fmt in ["md5"]:
fmt = "GFM"
minwidth = 5 # nopep8
if fmt in ["md6"]:
fmt = "GFM"
minwidth = 6 # nopep8
if fmt in ["wide"]:
fmt = "GFM"
tab = "" # nopep8
if fmt in ["read"]:
fmt = "GFM"
tab = " " # nopep8
padding = ""
noheaders = True
if fmt in ["txt"]:
fmt = "GFM"
padding = "" # nopep8
if fmt in ["text"]:
fmt = "GFM"
padding = ""
noheaders = True # nopep8
if fmt in ["tabs"]:
fmt = "GFM"
tab = "\t"
padding = "" # nopep8
if fmt in ["tab"]:
fmt = "CSV"
tab = "\t" # nopep8
if fmt in ["data"]:
fmt = "CSV"
tab = "\t"
noheaders = True # nopep8
if fmt in ["ifs"]:
fmt = "CSV"
tab = os.environ.get("IFS", "\t") # nopep8
if fmt in ["dat"]:
fmt = "CSV"
tab = os.environ.get("IFS", "\t")
noheaders = True # nopep8
if fmt in ["csv", "scsv"]:
fmt = "CSV"
tab = ";" # nopep8
if fmt in ["list"]:
fmt = "CSV"
tab = ";"
noheaders = True # nopep8
if fmt in ["json"]:
fmt = "JSON"
if fmt in ["jsn"]:
fmt = "JSON"
padding = ""
if fmt in ["xlsx", "xls"]:
fmt = "XLS"
tab = "," # nopep8
# override
if "@tab" in spec:
tab = spec["@tab"]
if "@notab" in spec:
tab = ""
if "@nopadding" in spec:
padding = ""
if "@noheaders" in spec:
noheaders = True
if "@unique" in spec:
unique = True
#
none_string = "~"
true_string = "(yes)"