-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
excelize.py
3037 lines (2628 loc) · 111 KB
/
excelize.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
"""Copyright 2024 - 2025 The excelize Authors. All rights reserved. Use of this
source code is governed by a BSD-style license that can be found in the LICENSE
file.
Package excelize-py is a Python port of Go Excelize library, providing a set of
functions that allow you to write and read from XLAM / XLSM / XLSX / XLTM / XLTX
files. Supports reading and writing spreadsheet documents generated by Microsoft
Excel™ 2007 and later. Supports complex components by high compatibility, and
provided streaming API for generating or reading data from a worksheet with huge
amounts of data. This library needs Python version 3.9 or later.
"""
from dataclasses import fields
from datetime import datetime, date, time
from enum import Enum
from typing import Tuple, get_args, get_origin, List, Optional, Union
import types_go
from types_py import *
from ctypes import (
byref,
c_bool,
c_char_p,
c_char,
c_double,
c_int,
c_ubyte,
cast,
CDLL,
create_string_buffer,
POINTER,
pointer,
string_at,
)
import os
import platform
def load_lib():
system = platform.system().lower()
arch = platform.architecture()[0]
machine = platform.machine().lower()
ext_map = {"linux": ".so", "darwin": ".dylib", "windows": ".dll"}
arch_map = {
"linux": {
"64bit": {
"x86_64": "amd64",
"amd64": "amd64",
"aarch64": "arm64",
},
"32bit": {
"x86": "386",
"i386": "386",
"i686": "386",
},
},
"darwin": {
"64bit": {
"x86_64": "amd64",
"amd64": "amd64",
"arm64": "arm64",
},
},
"windows": {
"64bit": {
"x86_64": "amd64",
"amd64": "amd64",
"arm64": "arm64",
},
"32bit": {
"x86": "386",
"i386": "386",
"i686": "386",
},
},
}
if system in ext_map and arch in arch_map.get(system, {}):
arch_name = arch_map[system][arch].get(machine)
if arch_name:
return f"libexcelize.{arch_name}.{system}{ext_map[system]}"
print("This platform or architecture is not supported.")
exit(1)
lib = CDLL(os.path.join(os.path.dirname(__file__), load_lib()))
ENCODE = "utf-8"
__version__ = "0.0.2"
uppercase_words = ["id", "rgb", "sq", "xml"]
def py_to_base_ctype(py_value, c_type):
"""
Convert a Python value to a specified C type.
Args:
py_value: The Python value to be converted. If the value is a string, it will be encoded.
c_type: The target C type to which the Python value should be converted.
Returns:
The converted value in the specified C type.
"""
return (
c_type(py_value.encode(ENCODE)) if str is type(py_value) else c_type(py_value)
)
def is_py_primitive_type(t: type) -> bool:
"""
Check if the given type is a Python primitive type.
Args:
t (type): The type to check.
Returns:
bool: True if the type is a Python primitive type or an Enum subclass, False otherwise.
"""
return True if issubclass(t, Enum) else t in {int, float, bool, str, bytes, complex}
def snake_to_pascal(snake_str: str) -> str:
"""
Convert a snake_case string to PascalCase.
Args:
snake_str (str): The snake_case string to convert.
Returns:
str: The converted PascalCase string.
"""
return "".join(
word.upper() if word.lower() in uppercase_words else word.capitalize()
for word in snake_str.split("_")
)
def c_value_to_py(ctypes_instance, py_instance):
"""
Convert a ctypes instance to a Python instance by mapping fields from the
to the corresponding fields in the Python instance.
Args:
ctypes_instance: The ctypes instance representing the Go data structure.
py_instance: The Python instance to populate with data from the ctypes instance.
Returns:
The populated Python instance, or None if the ctypes instance is None.
"""
if ctypes_instance is None:
return None
for py_field in fields(py_instance):
py_field_name = py_field.name
c_field_name = snake_to_pascal(py_field.name)
# The Go base type
py_field_args = get_args(py_field.type)
if type(None) not in py_field_args:
if is_py_primitive_type(py_field.type):
c_val = getattr(ctypes_instance, c_field_name)
if c_val:
setattr(
py_instance,
py_field_name,
(c_val.decode(ENCODE) if str is py_field.type else c_val),
)
continue
else:
# The Go struct, for example: excelize.Options, convert sub fields recursively
setattr(
py_instance,
py_field_name,
c_value_to_py(
getattr(ctypes_instance, c_field_name), py_field.type()
),
)
else:
if get_origin(py_field_args[0]) is not list:
# Pointer of the Go data type, for example: *excelize.Options or *string
value = getattr(ctypes_instance, c_field_name)
if value:
if any(is_py_primitive_type(arg) for arg in py_field_args):
# Pointer of the Go basic data type, for example: *string
value = getattr(ctypes_instance, c_field_name)
setattr(
py_instance,
py_field_name,
(
value.contents.value.decode(ENCODE)
if str in py_field_args
else value.contents.value
),
)
else:
# Pointer of the Go struct, for example: *excelize.Options
setattr(
py_instance,
py_field_name,
c_value_to_py(
value.contents,
py_field_args[0](),
),
)
else:
# The Go data type array, for example:
# []*excelize.Options, []excelize.Options, []string, []*string
if type(None) not in get_args(get_args(py_field_args[0])[0]):
# The Go data type array, for example: []excelize.Options or []string
py_list = []
l = getattr(ctypes_instance, c_field_name + "Len")
c_array = getattr(ctypes_instance, c_field_name)
if c_array:
if is_py_primitive_type(get_args(py_field_args[0])[0]):
# The Go basic data type array, for example: []string
for i in range(l):
py_list.append(
string_at(c_array[i]).decode(ENCODE)
if str is get_args(py_field_args[0])[0]
else c_array[i]
)
else:
# The Go struct array, for example: []excelize.Options
for i in range(l):
py_list.append(
c_value_to_py(
c_array[i],
get_args(py_field_args[0])[0](),
),
)
setattr(py_instance, py_field_name, py_list)
else:
# Pointer array of the Go data type, for example: []*excelize.Options or []*string
py_list = []
l = getattr(ctypes_instance, c_field_name + "Len")
c_array = getattr(ctypes_instance, c_field_name)
if c_array:
if is_py_primitive_type(
get_args(get_args(py_field_args[0])[0])[0]
):
# Pointer array of the Go basic data type, for example: []*string
for i in range(l):
py_list.append(
string_at(c_array[i]).decode(ENCODE)
if str is get_args(get_args(py_field_args[0])[0])[0]
else c_array[i].contents.value
)
else:
# Pointer array of the Go struct, for example: []*excelize.Options
for i in range(l):
py_list.append(
c_value_to_py(
c_array[i].contents,
get_args(get_args(py_field_args[0])[0])[0](),
),
)
setattr(py_instance, py_field_name, py_list)
return py_instance
def get_c_field_type(struct, field_name):
"""
Retrieve the type of a specified field from a C structure.
Args:
struct (ctypes.Structure): The C structure containing the fields.
field_name (str): The name of the field whose type is to be retrieved.
Returns:
type: The type of the specified field if found, otherwise None.
"""
for field in struct._fields_:
if field[0] == field_name:
return field[1]
def py_value_to_c(py_instance, ctypes_instance):
"""
Converts a Python instance to a corresponding C instance using ctypes.
This function recursively converts fields of a Python instance to their
corresponding C types and assigns them to the provided ctypes instance.
It handles primitive types, structs, pointers, and arrays.
Args:
py_instance (object): The Python instance to be converted.
ctypes_instance (ctypes.Structure): The ctypes instance to which the
converted values will be assigned.
Returns:
ctypes.Structure: The ctypes instance with the converted values from
the Python instance.
"""
if py_instance is None:
return None
for py_field in fields(py_instance):
py_field_name = py_field.name
c_field_name = snake_to_pascal(py_field.name)
# The Go base type
py_field_args = get_args(py_field.type)
if type(None) not in py_field_args:
if is_py_primitive_type(py_field.type):
if hasattr(py_instance, py_field_name):
c_type = get_c_field_type(ctypes_instance, c_field_name)
setattr(
ctypes_instance,
c_field_name,
py_to_base_ctype(getattr(py_instance, py_field_name), c_type),
)
continue
else:
# The Go struct, for example: excelize.Options, convert sub fields recursively
c_type = get_c_field_type(ctypes_instance, c_field_name)
if hasattr(py_instance, py_field_name):
setattr(
ctypes_instance,
c_field_name,
py_value_to_c(getattr(py_instance, py_field_name), c_type()),
)
else:
arg_type = py_field_args[0]
if get_origin(arg_type) is not list and arg_type is not bytes:
# Pointer of the Go data type, for example: *excelize.Options or *string
value = getattr(py_instance, py_field_name)
c_type = get_c_field_type(ctypes_instance, c_field_name)._type_
if value is not None:
if any(is_py_primitive_type(arg) for arg in py_field_args):
# Pointer of the Go basic data type, for example: *string
setattr(
ctypes_instance,
c_field_name,
pointer(py_to_base_ctype(value, c_type)),
)
else:
# Pointer of the Go struct, for example: *excelize.Options
setattr(
ctypes_instance,
c_field_name,
pointer(py_value_to_c(value, c_type())),
)
else:
# The Go data type array, for example:
# []*excelize.Options, []excelize.Options, []string, []*string
if arg_type is bytes: # []byte
c_type = get_c_field_type(ctypes_instance, c_field_name)._type_
value = getattr(py_instance, py_field_name)
ctypes_instance.__setattr__(
c_field_name, cast(value, POINTER(c_ubyte))
)
ctypes_instance.__setattr__(c_field_name + "Len", c_int(len(value)))
continue
py_field_type = get_args(arg_type)[0]
if type(None) not in get_args(py_field_type):
# The Go data type array, for example: []excelize.Options or []string
c_type = get_c_field_type(ctypes_instance, c_field_name)._type_
py_list = getattr(py_instance, py_field_name)
if py_list:
l = len(py_list)
c_array = (c_type * l)()
if is_py_primitive_type(py_field_type):
# The Go basic data type array, for example: []string
if str is py_field_type:
c_array_type = POINTER(c_char) * l
ctypes_instance.__setattr__(
c_field_name,
c_array_type(
*[
create_string_buffer(c.encode(ENCODE))
for c in py_list
]
),
)
else:
for i in range(l):
c_array.__setitem__(
i, py_to_base_ctype(py_list[i], c_type)
)
ctypes_instance.__setattr__(c_field_name, c_array)
else:
# The Go struct array, for example: []excelize.Options
for i in range(l):
c_array.__setitem__(
i, py_value_to_c(py_list[i], c_type())
)
ctypes_instance.__setattr__(c_field_name, c_array)
ctypes_instance.__setattr__(c_field_name + "Len", c_int(l))
else:
# Pointer array of the Go data type, for example: []*excelize.Options or []*string
c_type = get_c_field_type(
ctypes_instance, c_field_name
)._type_._type_
py_list = getattr(py_instance, py_field_name)
if py_list:
l = len(py_list)
c_array = (POINTER(c_type) * l)()
if is_py_primitive_type(get_args(py_field_type)[0]):
# Pointer array of the Go basic data type, for example: []*string
for i in range(l):
c_array.__setitem__(
i,
pointer(py_to_base_ctype(py_list[i], c_type)),
)
else:
# Pointer array of the Go struct, for example: []*excelize.Options
for i in range(l):
c_array.__setitem__(
i,
pointer(py_value_to_c(py_list[i], c_type())),
)
ctypes_instance.__setattr__(c_field_name + "Len", c_int(l))
ctypes_instance.__setattr__(c_field_name, c_array)
return ctypes_instance
def py_value_to_c_interface(py_value):
"""
Converts a Python value to a C interface representation.
Args:
py_value: The Python value to be converted.
Returns:
An Interface object representing the Python value in a C-compatible format.
Raises:
TypeError: If the type of py_value is not supported.
"""
type_mappings = {
int: lambda: Interface(type=1, integer=py_value),
str: lambda: Interface(type=2, string=py_value),
float: lambda: Interface(type=3, float64=py_value),
bool: lambda: Interface(type=4, boolean=py_value),
datetime: lambda: Interface(type=5, integer=int(py_value.timestamp())),
date: lambda: Interface(
type=5,
integer=int(datetime.combine(py_value, time.min).timestamp()),
),
}
interface = type_mappings.get(type(py_value), lambda: Interface())()
return py_value_to_c(interface, types_go._Interface())
class File:
file_index: int
def __init__(self, file_index):
self.file_index = file_index
def save(self, *opts: Options) -> Optional[Exception]:
"""
Override the spreadsheet with origin path.
Args:
*opts (Options): Optional parameters for saving the file.
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
err, lib.Save.restype = None, c_char_p
options = POINTER(types_go._Options)()
options = (
byref(py_value_to_c(opts[0], types_go._Options()))
if opts
else POINTER(types_go._Options)()
)
err = lib.Save(self.file_index, options).decode(ENCODE)
return None if err == "" else Exception(err)
def save_as(self, filename: str, *opts: Options) -> Optional[Exception]:
"""
Create or update to a spreadsheet at the provided path.
Args:
filename (str): The name of the file to save.
*opts (Options): Optional parameters for saving the file.
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.SaveAs.restype = c_char_p
options = (
byref(py_value_to_c(opts[0], types_go._Options()))
if opts
else POINTER(types_go._Options)()
)
err = lib.SaveAs(self.file_index, filename.encode(ENCODE), options).decode(
ENCODE
)
return None if err == "" else Exception(err)
def add_chart(
self, sheet: str, cell: str, chart: Chart, **combo: Chart
) -> Optional[Exception]:
"""
Add chart in a sheet by given chart format set (such as offset, scale,
aspect ratio setting and print settings) and properties set.
Args:
sheet (str): The worksheet name
cell (str): The cell reference
chart (Chart): Chart options
**combo (Chart): Optional parameters for combo chart
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddChart.restype = c_char_p
opts = [chart] + list(combo.values())
charts = (types_go._Chart * len(opts))()
for i, opt in enumerate(opts):
charts[i] = py_value_to_c(opt, types_go._Chart())
err = lib.AddChart(
self.file_index,
sheet.encode(ENCODE),
cell.encode(ENCODE),
byref(charts),
len(charts),
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_chart_sheet(
self, sheet: str, chart: Chart, **combo: Chart
) -> Optional[Exception]:
"""
Create a chartsheet by given chart format set (such as offset, scale,
aspect ratio setting and print settings) and properties set. In Excel a
chartsheet is a worksheet that only contains a chart.
Args:
sheet (str): The worksheet name
chart (Chart): Chart options
**combo (Chart): Optional parameters for combo chart
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddChartSheet.restype = c_char_p
opts = [chart] + list(combo.values())
charts = (types_go._Chart * len(opts))()
for i, opt in enumerate(opts):
charts[i] = py_value_to_c(opt, types_go._Chart())
err = lib.AddChartSheet(
self.file_index,
sheet.encode(ENCODE),
byref(charts),
len(charts),
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_comment(self, sheet: str, opts: Comment) -> Optional[Exception]:
"""
Add comments in a sheet by giving the worksheet name, cell reference,
and format set (such as author and text). Note that the maximum author
name length is 255 and the max text length is 32512.
Args:
sheet (str): The worksheet name
opts (Comment): The comment options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddComment.restype = c_char_p
options = py_value_to_c(opts, types_go._Comment())
err = lib.AddComment(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_form_control(self, sheet: str, opts: FormControl) -> Optional[Exception]:
"""
Add form control button in a worksheet by given worksheet name and form
control options. Supported form control type: button, check box, group
box, label, option button, scroll bar and spinner. If set macro for the
form control, the workbook extension should be XLSM or XLTM. Scroll
value must be between 0 and 30000.
Args:
sheet (str): The worksheet name
opts (FormControl): The form control options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddFormControl.restype = c_char_p
options = py_value_to_c(opts, types_go._FormControl())
err = lib.AddFormControl(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_picture(
self, sheet: str, cell: str, name: str, opts: Optional[GraphicOptions]
) -> Optional[Exception]:
"""
Add picture in a sheet by given picture format set (such as offset,
scale, aspect ratio setting and print settings) and file path, supported
image types: BMP, EMF, EMZ, GIF, JPEG, JPG, PNG, SVG, TIF, TIFF, WMF,
and WMZ.
Args:
sheet (str): The worksheet name
cell (str): The cell reference
name (str): The image file path
*opts (GraphicOptions): The image options
Returns:
Optional[GraphicOptions]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddPicture.restype = c_char_p
options = (
byref(py_value_to_c(opts, types_go._GraphicOptions()))
if opts
else POINTER(types_go._GraphicOptions)()
)
err = lib.AddPicture(
self.file_index,
sheet.encode(ENCODE),
cell.encode(ENCODE),
name.encode(ENCODE),
options,
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_picture_from_bytes(
self, sheet: str, cell: str, picture: Picture
) -> Optional[Exception]:
"""
Add picture in a sheet by given picture format set (such as offset,
scale, aspect ratio setting and print settings), file base name,
extension name and file bytes, supported image types: EMF, EMZ, GIF,
JPEG, JPG, PNG, SVG, TIF, TIFF, WMF, and WMZ. Note that this function
only supports adding pictures placed over the cells currently, and
doesn't support adding pictures placed in cells or creating the Kingsoft
WPS Office embedded image cells
Args:
sheet (str): The worksheet name
extension (str): The image extension
picture (Picture): The picture options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddPictureFromBytes.restype = c_char_p
err = lib.AddPictureFromBytes(
self.file_index,
sheet.encode(ENCODE),
cell.encode(ENCODE),
byref(py_value_to_c(picture, types_go._Picture())),
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_pivot_table(self, opts: Optional[PivotTableOptions]) -> Optional[Exception]:
"""
Add pivot table by given pivot table options. Note that the same fields
can not in Columns, Rows and Filter fields at the same time.
Args:
opts (PivotTableOptions): The pivot table options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
Example:
For example, create a pivot table on the range reference
Sheet1!G2:M34 with the range reference Sheet1!A1:E31 as the data
source, summarize by sum for sales:
.. code-block:: python
import excelize
import random
f = excelize.new_file()
month = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
]
year = [2017, 2018, 2019]
types = ["Meat", "Dairy", "Beverages", "Produce"]
region = ["East", "West", "North", "South"]
err = f.set_sheet_row("Sheet1", "A1", ["Month", "Year", "Type", "Sales", "Region"])
if err:
print(err)
for row in range(2, 32):
err = f.set_cell_value("Sheet1", f"A{row}", month[random.randrange(12)])
if err:
print(err)
err = f.set_cell_value("Sheet1", f"B{row}", year[random.randrange(3)])
if err:
print(err)
err = f.set_cell_value("Sheet1", f"C{row}", types[random.randrange(4)])
if err:
print(err)
err = f.set_cell_value("Sheet1", f"D{row}", random.randrange(5000))
if err:
print(err)
err = f.set_cell_value("Sheet1", f"E{row}", region[random.randrange(4)])
if err:
print(err)
err = f.add_pivot_table(
excelize.PivotTableOptions(
data_range="Sheet1!A1:E31",
pivot_table_range="Sheet1!G2:M34",
rows=[
excelize.PivotTableField(data="Month", default_subtotal=True),
excelize.PivotTableField(data="Year"),
],
filter=[excelize.PivotTableField(data="Region")],
columns=[
excelize.PivotTableField(data="Type", default_subtotal=True),
],
data=[
excelize.PivotTableField(data="Sales", name="Summarize", subtotal="Sum"),
],
row_grand_totals=True,
col_grand_totals=True,
show_drill=True,
show_row_headers=True,
show_col_headers=True,
show_last_column=True,
)
)
if err:
print(err)
err = f.save_as("Book1.xlsx")
if err:
print(err)
err = f.close()
if err:
print(err)
"""
lib.AddPivotTable.restype = c_char_p
err = lib.AddPivotTable(
self.file_index,
byref(py_value_to_c(opts, types_go._PivotTableOptions())),
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_shape(self, sheet: str, opts: Shape) -> Optional[Exception]:
"""
Add shape in a sheet by given worksheet name and shape format set (such
as offset, scale, aspect ratio setting and print settings).
Args:
sheet (str): The worksheet name
opts (Shape): The shape options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
Example:
For example, add text box (rect shape) in Sheet1:
.. code-block:: python
import excelize
f = excelize.new_file()
err = f.add_shape(
"Sheet1",
excelize.Shape(
cell="G6",
type="rect",
line=excelize.ShapeLine(
color="4286F4",
width=1.2,
),
fill=excelize.Fill(
color=["8EB9FF"],
pattern=1,
),
paragraph=[
excelize.RichTextRun(
text="Rectangle Shape",
font=excelize.Font(
bold=True,
italic=True,
family="Times New Roman",
size=19,
color="777777",
underline="sng",
),
)
],
width=80,
height=40,
),
)
if err:
print(err)
err = f.save_as("Book1.xlsx")
if err:
print(err)
err = f.close()
if err:
print(err)
"""
lib.AddShape.restype = c_char_p
options = py_value_to_c(opts, types_go._Shape())
err = lib.AddShape(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_slicer(self, sheet: str, opts: SlicerOptions) -> Optional[Exception]:
"""
Inserts a slicer by giving the worksheet name and slicer settings.
Args:
sheet (str): The worksheet name
opts (SlicerOptions): The slicer options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
Example:
For example, insert a slicer on the Sheet1!E1 with field Column1 for
the table named Table1:
.. code-block:: python
err = f.add_slicer(
"Sheet1",
excelize.SlicerOptions(
name="Column1",
cell="E1",
table_sheet="Sheet1",
table_name="Table1",
caption="Column1",
width=200,
height=200,
),
)
"""
lib.AddSlicer.restype = c_char_p
options = py_value_to_c(opts, types_go._SlicerOptions())
err = lib.AddSlicer(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_sparkline(self, sheet: str, opts: SparklineOptions) -> Optional[Exception]:
"""
add sparklines to the worksheet by given formatting options. Sparklines
are small charts that fit in a single cell and are used to show trends
in data. Sparklines are a feature of Excel 2010 and later only. You can
write them to workbook that can be read by Excel 2007, but they won't be
displayed.
Args:
sheet (str): The worksheet name
opts (SparklineOptions): The sparklines options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
Example:
For example, add a grouped sparkline. Changes are applied to all
three:
.. code-block:: python
err = f.add_sparkline(
"Sheet1",
excelize.SparklineOptions(
location=["A1", "A2", "A3"],
range=["Sheet2!A1:J1", "Sheet2!A2:J2", "Sheet2!A3:J3"],
markers=True,
),
)
"""
lib.AddSparkline.restype = c_char_p
options = py_value_to_c(opts, types_go._SparklineOptions())
err = lib.AddSparkline(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_table(self, sheet: str, table: Table) -> Optional[Exception]:
"""
Add table in a worksheet by given worksheet name, range reference and
format set.
Note that the table must be at least two lines including the header. The
header cells must contain strings and must be unique, and must set the
header row data of the table before calling the AddTable function.
Multiple tables range reference that can't have an intersection.
Args:
sheet (str): The worksheet name
table (Table): The table options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
Example:
For example, create a table of A1:D5 on Sheet1:
.. code-block:: python
err = f.add_table("Sheet1", excelize.Table(range="A1:D5"))
"""
lib.AddTable.restype = c_char_p
options = py_value_to_c(table, types_go._Table())
err = lib.AddTable(
self.file_index, sheet.encode(ENCODE), byref(options)
).decode(ENCODE)
return None if err == "" else Exception(err)
def add_vba_project(self, file: bytes) -> Optional[Exception]:
"""
Add vbaProject.bin file which contains functions and/or macros. The file
extension should be XLSM or XLTM.
Args:
file (bytes): The contents buffer of the file
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddVBAProject.restype = c_char_p
err = lib.AddVBAProject(
self.file_index,
cast(file, POINTER(c_ubyte)),
len(file),
).decode(ENCODE)
return None if err == "" else Exception(err)
def auto_filter(
self,
sheet: str,
range_ref: str,
opts: List[AutoFilterOptions],
) -> Optional[Exception]:
"""
Add auto filter in a worksheet by given worksheet name, range reference
and settings. An auto filter in Excel is a way of filtering a 2D range
of data based on some simple criteria.
Column defines the filter columns in an auto filter range based on simple
criteria
It isn't sufficient to just specify the filter condition. You must also
hide any rows that don't match the filter condition. Rows are hidden using
the SetRowVisible function. Excelize can't filter rows automatically since
this isn't part of the file format.
Args:
sheet (str): The worksheet name
range_ref (str): The top-left and right-bottom cell range reference
opts (List[AutoFilterOptions]): The auto filter options
Returns:
Optional[Exception]: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AutoFilter.restype = c_char_p
options = (types_go._AutoFilterOptions * len(opts))()
for i, opt in enumerate(opts):
options[i] = py_value_to_c(opt, types_go._AutoFilterOptions())
err = lib.AutoFilter(
self.file_index,
sheet.encode(ENCODE),
range_ref.encode(ENCODE),
byref(options),
len(options),
).decode(ENCODE)
return None if err == "" else Exception(err)
def calc_cell_value(
self, sheet: str, cell: str, *opts: Options
) -> Tuple[str, Optional[Exception]]:
"""
Get calculated cell value. This feature is currently in working
processing. Iterative calculation, implicit intersection, explicit
intersection, array formula, table formula and some other formulas are
not supported currently.
Args:
sheet (str): The worksheet name
cell (str): The cell reference
*opts (Options): Optional parameters for get cell value
Returns: