pyxll 5.13.0__cp315-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyxll/__init__.py ADDED
@@ -0,0 +1,3924 @@
1
+ """
2
+ Copyright PyXLL Ltd
3
+ www.pyxll.com
4
+
5
+ PyXLL allows you to create Excel addins written in Python.
6
+
7
+ *************************************************************************
8
+ * IMPORTANT: *
9
+ * This module is NOT the actual pyxll module used when your PyXLL *
10
+ * addin runs in Excel. *
11
+ * *
12
+ * It is just a module of stubs functions so that you can import pyxll *
13
+ * from other python interpreters outside of Excel (for unit testing, *
14
+ * for example). *
15
+ *************************************************************************
16
+
17
+ This module contains decorators used by the PyXLL Excel addin to expose
18
+ python functions as worksheet functions, macro functions and menu items
19
+ to Excel.
20
+
21
+ For full documentation please refer to www.pyxll.com.
22
+ """
23
+ import warnings
24
+ import logging
25
+ import sys
26
+
27
+ import typing
28
+
29
+ _log = logging.getLogger(__name__)
30
+
31
+ try:
32
+ from xml.dom import minidom
33
+ _have_minidom = True
34
+ except ImportError:
35
+ minidom = None # type: ignore
36
+
37
+ __version__ = "5.13.0"
38
+
39
+ nan = 1e10000 * 0
40
+
41
+ xlCalculationAutomatic = 1
42
+ xlCalculationSemiAutomatic = 2
43
+ xlCalculationManual = 3
44
+
45
+ xlDialogTypeNone = 0
46
+ xlDialogTypeFunctionWizard = 1
47
+ xlDialogTypeSearchAndReplace = 2
48
+
49
+ _no_value = object()
50
+
51
+ def reload():
52
+ """
53
+ Causes the PyXLL addin and any modules listed in the config file to be reloaded
54
+ once the calling function has returned control back to Excel.
55
+
56
+ If the `deep_reload` configuration option is turned on then any dependencies
57
+ of the modules listed in the config file will also be reloaded.
58
+
59
+ The Python interpreter is not restarted.
60
+ """
61
+ raise Exception("Not supported when running outside of Excel")
62
+
63
+ def com_reload():
64
+ """
65
+ Causes the COM part of the PyXLL addin to be reloaded once the calling function
66
+ has returned control back to Excel.
67
+
68
+ This doesn't reload any Python modules or rebind any functions. The COM addin
69
+ is responsible for the ribbon user interface and reloading it will cause the
70
+ ribbon to be reloaded.
71
+ """
72
+ raise Exception("Not supported when running outside of Excel")
73
+
74
+ def rebind():
75
+ """
76
+ Causes the PyXLL addin to rebuild the bindings between the exposed Python
77
+ functions and Excel once the calling function has returned control back to Excel.
78
+
79
+ This can be useful when importing modules or declaring new Python functions
80
+ dynamically and you want newly imported or created Python functions to be exposed to Excel without reloading.
81
+
82
+ Example usage::
83
+
84
+ from pyxll import xl_macro, rebind
85
+
86
+ @xl_macro
87
+ def load_python_modules():
88
+ import another_module_with_pyxll_functions
89
+ rebind()
90
+ """
91
+ raise Exception("Not supported when running outside of Excel")
92
+
93
+ def about():
94
+ """
95
+ Show the PyXLL 'about' dialog.
96
+ """
97
+ raise Exception("Not supported when running outside of Excel")
98
+
99
+ def xl_arg_type(name, # type: str
100
+ base_type, # type: str
101
+ allow_arrays=True, # type: bool
102
+ macro=None, # type: typing.Union[bool, None]
103
+ thread_safe=None, # type: typing.Union[bool, None]
104
+ typing_type=None # type: typing.Union[typing.Type, None]
105
+ ): # type: (...) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Callable[..., typing.Any]]
106
+ """
107
+ Decorator for adding custom types for use with
108
+ functions exposed via xl_func and xl_macro.
109
+ eg:
110
+
111
+ class myobject:
112
+ def __init__(self, name):
113
+ self.name = name
114
+
115
+ @xl_arg_type("myobject", "string")
116
+ def myobject_from_string(name):
117
+ return myobject(name)
118
+
119
+ @xl_func("myobject obj: string")
120
+ def get_name(obj):
121
+ return obj.name
122
+
123
+ in this example, get_name is called from excel with a string argument
124
+ that is converted to a myobject instance via myobject_from_string.
125
+
126
+ If allow_arrays is True, arrays of the custom type are allowed
127
+ using the standard signature notation 'myobject[]' (for the example
128
+ above).
129
+
130
+ macro and thread_safe can be set if the function using this type
131
+ must be a macro equivalent function (set macro=True) or must not
132
+ be registered as thread safe (set thread_safe=False).
133
+ """
134
+ def dummy_decorator(func):
135
+ return func
136
+ return dummy_decorator
137
+
138
+ def xl_return_type(name, # type: str
139
+ base_type, # type: str
140
+ allow_arrays=True, # type: bool
141
+ macro=None, # type: typing.Union[bool, None]
142
+ thread_safe=None, # type: typing.Union[bool, None]
143
+ typing_type=None # type: typing.Union[typing.Type, None]
144
+ ): # type: (...) -> _Decorator
145
+ """
146
+ Decorator for adding custom types for use with
147
+ functions exposed via xl_func and xl_macro.
148
+ eg:
149
+
150
+ class myobject:
151
+ def __init__(self, name):
152
+ self.name = name
153
+
154
+ @xl_return_type("myobject", "string")
155
+ def myobject_to_string(obj):
156
+ return obj.name
157
+
158
+ @xl_func("string name: myobject")
159
+ def get_object(name):
160
+ return myobject(name)
161
+
162
+ in this example, get_object is called from excel with a string
163
+ argument and returns a myobject instance. That is converted to a
164
+ string by the registered myobject_to_string function and returned
165
+ to excel as a string.
166
+
167
+ If allow_arrays is True, arrays of the custom type are allowed
168
+ using the standard signature notation 'myobject[]' (for the example
169
+ above).
170
+
171
+ macro and thread_safe can be set if the function using this type
172
+ must be a macro equivalent function (set macro=True) or must not
173
+ be registered as thread safe (set thread_safe=False).
174
+ """
175
+ def dummy_decorator(func):
176
+ return func
177
+ return dummy_decorator
178
+
179
+ def xl_return(_type=None, # type: typing.Union[str, None]
180
+ **kwargs):
181
+ # type: (...) -> _Decorator
182
+ """
183
+ Add type information for a function's return type.
184
+
185
+ This can be used instead or as well as providing the return type information
186
+ in the function signature.
187
+
188
+ Using this decorator can be simpler when the return type is generic and requires
189
+ complex type arguments.
190
+
191
+ @xl_func
192
+ @xl_return("dataframe", index=True, columns=True)
193
+ def return_pandas_dataframe():
194
+ pass
195
+
196
+ :param _type: Type expected to be returned by the function
197
+ :param kwargs: Keyword arguments provided to the return type converter
198
+ """
199
+ def dummy_decorator(func):
200
+ return func
201
+ return dummy_decorator
202
+
203
+ def xl_arg(_name, # type: str
204
+ _type=None, # type: typing.Union[str, None]
205
+ _label=None, # type: typing.Union[str, None]
206
+ _description=None, # type: typing.Union[str, None]
207
+ **kwargs):
208
+ # type: (...) -> _Decorator
209
+ """
210
+ Add type information for a function's argument type.
211
+
212
+ This can be used instead or as well as providing the return type information
213
+ in the function signature.
214
+
215
+ Using this decorator can be simpler when the return type is generic and requires
216
+ complex type arguments.
217
+
218
+ @xl_func
219
+ @xl_arg("x", "dataframe", index=True, columns=True)
220
+ def return_pandas_dataframe(x):
221
+ pass
222
+
223
+ :param _name: Name of the argument this relates to.
224
+ :param _type: Type expected for the argument.
225
+ :param _label: Label to show in Excel function help for the argument.
226
+ :param _description: Argument description to show in Excel function help for the argument.
227
+ :param kwargs: Keyword arguments provided to the argument type converter.
228
+ """
229
+ def dummy_decorator(func):
230
+ return func
231
+ return dummy_decorator
232
+
233
+ def get_type_converter(src_type, # type: typing.Union[str, typing.Type]
234
+ dest_type, # type: typing.Union[str, typing.Type]
235
+ src_kwargs={}, # type: typing.Dict[str, typing.Any]
236
+ dest_kwargs={} # type: typing.Dict[str, typing.Any]
237
+ ): # type: (...) -> typing.Callable[[typing.Any], typing.Any]
238
+ """
239
+ Return a function that converts from one type registered
240
+ with PyXLL to another.
241
+
242
+ When this function is called from outside of Excel then it
243
+ is purely a stub function. It returns a dummy function that simply
244
+ returns the argument it is passed.
245
+
246
+ This is so the functions can be written that take var arguments when
247
+ called from Excel and use PyXLL's type conversion to convert to proper
248
+ python types, but accept proper python types when called from other python
249
+ code outside of Excel (e.g. when testing in an interactive prompt or in
250
+ unit tests).
251
+
252
+ For example::
253
+
254
+ @xl_func("var a_date: var")
255
+ def test_func(a_date):
256
+ if a_date is not None:
257
+ var_to_date = get_type_converter("var", "date")
258
+ a_date = var_to_date(a_date) # does nothing if not called in Excel
259
+ return a_date.strftime("%Y-%m-%d")
260
+
261
+ >> test_func(datetime.date(2014,2,11))
262
+ '2014-02-11'
263
+ """
264
+ # This is a dummy function here only so it can be imported and does not perform
265
+ # any type conversion when no imported from inside Excel.
266
+ return lambda x: x
267
+
268
+ def get_active_object():
269
+ # type: () -> _ExcelApplication
270
+ """
271
+ Deprecated. Use xl_app instead.
272
+ """
273
+ warnings.warn("pyxll.get_active_object is deprecated. Use xl_app instead.", DeprecationWarning)
274
+
275
+ # this is only used when calling from outside Excel.
276
+ # the builtin pyxll module does 'the right thing'.
277
+ xl = xl_app()
278
+ return xl.Windows[0]
279
+
280
+ def xl_app(com_package="win32com"):
281
+ # type: (typing.Union[str, None]) -> _ExcelApplication
282
+ """
283
+ Return the COM Excel Application object for the Excel
284
+ instance the PyXLL addin is running in.
285
+
286
+ When called from outside of Excel, this will return the first
287
+ open Excel found. If there is no Excel window open, this
288
+ function will raise and Exception.
289
+ """
290
+ # this is only used when calling from outside Excel.
291
+ # the builtin pyxll module does 'the right thing'.
292
+ if com_package == "pythoncom":
293
+ import pythoncom # type: ignore
294
+ return pythoncom.GetActiveObject("Excel.Application")
295
+
296
+ elif com_package == "win32com":
297
+ import pythoncom # type: ignore
298
+ xl = pythoncom.GetActiveObject("Excel.Application")
299
+ return _wrap_iunknown(xl)
300
+
301
+ elif com_package == "comtypes":
302
+ import comtypes.client # type: ignore
303
+ return comtypes.client.GetActiveObject("Excel.Application")
304
+
305
+ elif com_package == "xlwings":
306
+ import xlwings # type: ignore
307
+ try:
308
+ version = tuple(map(int, xlwings.__version__.split(".")[:2]))
309
+ except Exception:
310
+ _log.warning("Error parsing xlwings version '%s'" % xlwings.__version__)
311
+ version = (0, 0)
312
+ assert version >= (0, 9), "xlwings >= 0.9 required (%s is installed)" % xlwings.__version__
313
+ if xlwings.apps.count == 0:
314
+ return xlwings.App()
315
+ return xlwings.apps.active
316
+
317
+ else:
318
+ raise ValueError("Unexpected com_package '%s'" % com_package)
319
+
320
+ def get_dialog_type():
321
+ # type: () -> int
322
+ """
323
+ Returns a value indicating what type of dialog a function was
324
+ called from, if any.
325
+
326
+ This can be used to disable slow running calculations in the
327
+ function wizard or when doing a search and replace operation.
328
+ """
329
+ return xlDialogTypeNone
330
+
331
+ def get_last_error(cell):
332
+ # type: (Union[XLCell, exceltypes.Range]) -> _OptExcInfo
333
+ """
334
+ When a Python function is called from an Excel worksheet, if an uncaught exception is raised PyXLL
335
+ caches the exception and traceback as well as logging it to the log file.
336
+
337
+ The last exception raised while evaluating a cell can be retrieved using this function.
338
+
339
+ The cache used by PyXLL to store thrown exceptions is limited to a maximum size, and so if there are
340
+ more cells with errors than the cache size the least recently thrown exceptions are discarded. The
341
+ cache size may be set via the error_cache_size setting in the config file.
342
+
343
+ When a cell returns a value and no exception is thrown any previous error is **not** discarded. This
344
+ is because doing so would add additional performance overhead to every function call.
345
+
346
+ :param xl_cell: XLCell instance or a COM Range object (the exact type depends
347
+ on the com_package setting in the config file.
348
+
349
+ :return: The last exception raised by a Python function evaluated in the cell, as a tuple
350
+ (type, value, traceback).
351
+
352
+ Example usage::
353
+
354
+ from pyxll import xl_func, xl_menu, xl_version, get_last_error
355
+ import traceback
356
+
357
+ @xl_func("xl_cell: string")
358
+ def python_error(cell):
359
+ exc_type, exc_value, exc_traceback = pyxll.get_last_error(cell)
360
+ if exc_type is None:
361
+ return "No error"
362
+
363
+ return "".join(traceback.format_exception_only(exc_type, exc_value))
364
+ """
365
+ raise Exception("Not supported when running outside of Excel")
366
+
367
+ def cached_object_count():
368
+ # type: () -> int
369
+ """Return the number of objects cached in the internal object cache"""
370
+ return 0
371
+
372
+ def message_box(message, caption="", flags=0):
373
+ # type: (str, str, int) -> None
374
+ """Show a message dialog box."""
375
+ import win32api # type: ignore
376
+ return win32api.MessageBox(None, message, caption, flags)
377
+
378
+ def xlfGetDocument(arg_num, name=None):
379
+ raise Exception("Not supported when running outside of Excel")
380
+
381
+ def xlfGetWorkspace(arg_num):
382
+ raise Exception("Not supported when running outside of Excel")
383
+
384
+ def xlfGetWorkbook(arg_num, workbook_name=None):
385
+ raise Exception("Not supported when running outside of Excel")
386
+
387
+ def xlfGetWindow(arg_num, workbook_name=None):
388
+ raise Exception("Not supported when running outside of Excel")
389
+
390
+ def xlfWindows(match_type=None, mask=None):
391
+ raise Exception("Not supported when running outside of Excel")
392
+
393
+ def xlfCaller():
394
+ # type: () -> XLCell
395
+ raise Exception("Not supported when running outside of Excel")
396
+
397
+ def xlAsyncReturn(async_handle, value):
398
+ raise Exception("Not supported when running outside of Excel")
399
+
400
+ def xlcAlert(message):
401
+ # type: (str) -> None
402
+ raise Exception("Not supported when running outside of Excel")
403
+
404
+ def xlcCalculation(calculation_type):
405
+ raise Exception("Not supported when running outside of Excel")
406
+
407
+ def xlcCalculateNow():
408
+ raise Exception("Not supported when running outside of Excel")
409
+
410
+ def xlcCalculateDocument():
411
+ raise Exception("Not supported when running outside of Excel")
412
+
413
+ def xlAbort(retain=True):
414
+ raise Exception("Not supported when running outside of Excel")
415
+
416
+ def xlSheetNm(sheet_id):
417
+ raise Exception("Not supported when running outside of Excel")
418
+
419
+ def xlSheetId(sheet_name):
420
+ raise Exception("Not supported when running outside of Excel")
421
+
422
+ def xlfVolatile(volatile):
423
+ # has no effect when running outside of Excel
424
+ pass
425
+
426
+ class XLAsyncHandle(object):
427
+ caller = None
428
+ function_name = None
429
+
430
+ def __init__(self, *args, **kwargs):
431
+ raise Exception("Not supported when running outside of Excel")
432
+
433
+ def set_value(self, value):
434
+ raise Exception("Not supported when running outside of Excel")
435
+
436
+ def set_error(self,
437
+ exc_type, # type: Type[BaseException]
438
+ exc_value, # type: BaseException
439
+ exc_traceback # type: types.TracebackType
440
+ ):
441
+ raise Exception("Not supported when running outside of Excel")
442
+
443
+ if sys.version_info[:3] >= (3, 5, 1):
444
+ import asyncio
445
+
446
+ def get_event_loop():
447
+ # type: () -> asyncio.AbstractEventLoop
448
+ """
449
+ Get the async event loop used by PyXLL for scheduling async tasks.
450
+
451
+ If called in Excel and the event loop is not already running it is
452
+ started in a background thread.
453
+
454
+ If called outside of Excel then the event loop is returned
455
+ without starting it.
456
+
457
+ :return: asyncio.AbstractEventLoop
458
+ """
459
+ return asyncio.get_event_loop()
460
+
461
+ def get_config():
462
+ # type: () -> configparser.ConfigParser
463
+ """returns the PyXLL config as a ConfigParser.RawConfigParser instance"""
464
+ raise Exception("Not supported when running outside of Excel")
465
+
466
+ def xl_version():
467
+ # type: () -> float
468
+ """
469
+ returns the version of Excel the addin is running in as a float.
470
+
471
+ 8.0 => Excel 97
472
+ 9.0 => Excel 2000
473
+ 10.0 => Excel 2002
474
+ 11.0 => Excel 2003
475
+ 12.0 => Excel 2007
476
+ 14.0 => Excel 2010
477
+ """
478
+ raise Exception("Not supported when running outside of Excel")
479
+
480
+ _RTD_T = typing.TypeVar("_RTD_T")
481
+
482
+ class RTD(typing.Generic[_RTD_T]):
483
+ def __init__(self, value=None):
484
+ self.__value = value
485
+ self.__error = None
486
+
487
+ def __get_value(self):
488
+ return self.__value
489
+
490
+ def __set_value(self, value):
491
+ self.__value = value
492
+ self.__error = None
493
+
494
+ value = property(__get_value, __set_value)
495
+
496
+ def connect(self):
497
+ """Called when Excel connects to this RTD instance, which occurs shortly after an
498
+ Excel function has returned an RTD object.
499
+
500
+ May be overridden in the sub-class.
501
+
502
+ Since PyXLL 4.2.0: May be an async method.
503
+ """
504
+ pass
505
+
506
+ def disconnect(self):
507
+ """Called when Excel no longer needs the RTD instance. This is usually because there are no longer
508
+ any cells that need it or because Excel is shutting down.
509
+
510
+ May be overridden in the sub-class.
511
+
512
+ Since PyXLL 4.2.0: May be an async method.
513
+ """
514
+ pass
515
+
516
+ @property
517
+ def connected(self):
518
+ return False
519
+
520
+ @property
521
+ def disconnected(self):
522
+ return False
523
+
524
+ def detach(self):
525
+ """Detaches the RTD instance from any Excel RTD functions.
526
+
527
+ After detaching, any subsequent calls to the Excel RTD function that created
528
+ this object will result in the Python function be re-run.
529
+
530
+ See `Restarting RTD Functions` in the user guide for more details.
531
+ """
532
+ pass
533
+
534
+ def set_error(self,
535
+ exc_type, # type: typing.Type[BaseException]
536
+ exc_value, # type: BaseException
537
+ exc_traceback # type: types.TracebackType
538
+ ):
539
+ """Update Excel with an error. E.g.::
540
+
541
+ def update(self):
542
+ try:
543
+ self.value = get_new_value()
544
+ except:
545
+ self.set_error(*sys.exc_info())
546
+ """
547
+ self.__error = (exc_type, exc_value, exc_traceback)
548
+
549
+ class XLCell(object):
550
+
551
+ value = None # type: typing.Any
552
+
553
+ def __init__(self, *args, **kwargs):
554
+ raise Exception("Not supported when running outside of Excel")
555
+
556
+ @staticmethod
557
+ def from_range(range):
558
+ # type: (typing.Union[_ExcelRange, str]) -> XLCell
559
+ raise Exception("Not supported when running outside of Excel")
560
+
561
+ def to_range(self, com_package=None):
562
+ # type: (typing.Union[str, None]) -> _ExcelRange
563
+ """Return an Excel.Range object using the COM package specified.
564
+ :param com_package: COM package to use to return the COM Range object.
565
+ May be any of:
566
+ - win32com
567
+ - comtypes
568
+ - xlwings
569
+ """
570
+ raise Exception("Not supported when running outside of Excel")
571
+
572
+ def options(self,
573
+ type=None, # type: typing.Union[str, typing.Type, None]
574
+ auto_resize=None, # type: typing.Union[bool, None]
575
+ type_kwargs=None, # type: typing.Union[typing.Dict[str, typing.Any], None]
576
+ formatter=None, # type: typing.Union[BaseFormatter, None]
577
+ nan_value=_no_value, # type: typing.Any
578
+ posinf_value=_no_value, # type: typing.Any
579
+ neginf_value=_no_value # type: typing.Any
580
+ ): # type: (...) -> XLCell
581
+ """Set options that control how values are retrieved and set.
582
+
583
+ :param type: Type to convert values to when getting.
584
+ :param auto_resize: If True, auto-resize when setting arrays.
585
+ :param type_kwargs: Options for type converter.
586
+ :param formatter: Formatter to apply when setting value.
587
+ :return: Return self so this method can easily be chained.
588
+ """
589
+ return self
590
+
591
+ @property
592
+ def rows(self):
593
+ # type: () -> int
594
+ """Return the number of rows in the range."""
595
+ raise Exception("Not supported when running outside of Excel")
596
+
597
+ @property
598
+ def columns(self):
599
+ # type: () -> int
600
+ """Return the number of columns in the range."""
601
+ raise Exception("Not supported when running outside of Excel")
602
+
603
+ def row(self, i):
604
+ # type: (int) -> XLCell
605
+ """Return a new XLCell for a row of this instance.
606
+
607
+ :param i: Index from 0 for the row to return.
608
+ """
609
+ raise Exception("Not supported when running outside of Excel")
610
+
611
+ def column(self, i):
612
+ # type: (int) -> XLCell
613
+ """Return a new XLCell for a column of this instance.
614
+
615
+ :param i: Index from 0 for the column to return.
616
+ """
617
+ raise Exception("Not supported when running outside of Excel")
618
+
619
+ def cell(self, row, column):
620
+ # type: (int, int) -> XLCell
621
+ """Return a new XLCell for an individual cell of this instance.
622
+
623
+ :param row: Index from 0 for the row to select.
624
+ :param column: Index from 0 for the column to select.
625
+ """
626
+ raise Exception("Not supported when running outside of Excel")
627
+
628
+ def offset(self, rows=0, columns=0):
629
+ # type: (int, int) -> XLCell
630
+ """Return a new XLCell offset from this one by rows and columns.
631
+
632
+ :param rows: Number of rows to offset by.
633
+ :param columns: Number of columns to offset by.
634
+ """
635
+ raise Exception("Not supported when running outside of Excel")
636
+
637
+ def resize(self, rows=None, columns=None):
638
+ # type: (typing.Union[int, None], typing.Union[int, None]) -> XLCell
639
+ """Return a new XLCell in the same top left location, resized to rows and columns.
640
+
641
+ :param rows: Number of rows after resizing, or None to keep the same.
642
+ :param columns: Number of columns after resizing, or None to keep the same.
643
+ """
644
+ raise Exception("Not supported when running outside of Excel")
645
+
646
+ class IRibbonUI:
647
+ """Wrapper for the Excel IRibbonUI COM interface.
648
+
649
+ The object that is returned by the onLoad procedure specified
650
+ on the customUI tag. The object contains methods for invalidating
651
+ control properties and for refreshing the user interface.
652
+
653
+ The IRibbonUI object does not generate events in its interaction
654
+ with the user. Instead, ribbon elements perform callbacks to your
655
+ code, and the linkage between ribbon elements and your code is
656
+ defined in the XML that describes your ribbon additions.
657
+ """
658
+
659
+ def Invalidate(self):
660
+ raise Exception("Not supported when running outside of Excel")
661
+
662
+ def InvalidateControl(self,
663
+ control_id # type: str
664
+ ):
665
+ raise Exception("Not supported when running outside of Excel")
666
+
667
+ def InvalidateControlMso(self,
668
+ control_id # type: str
669
+ ):
670
+ raise Exception("Not supported when running outside of Excel")
671
+
672
+ def ActivateTab(self,
673
+ tab_id # type: str
674
+ ):
675
+ raise Exception("Not supported when running outside of Excel")
676
+
677
+ def ActivateTabMso(self,
678
+ tab_id # type: str
679
+ ):
680
+ raise Exception("Not supported when running outside of Excel")
681
+
682
+ def ActivateTabQ(self,
683
+ tab_id # type: str
684
+ ):
685
+ raise Exception("Not supported when running outside of Excel")
686
+
687
+ class IRibbonControl:
688
+ """Wrapper for the Excel IRibbonControl COM interface.
689
+
690
+ Represents the object passed into the callback procedure of a control
691
+ in a ribbon or another user interface that can be customized by using
692
+ Office Fluent ribbon extensibility.
693
+ """
694
+
695
+ @property
696
+ def Id(self): # type: (...) -> str
697
+ raise Exception("Not supported when running outside of Excel")
698
+
699
+ @property
700
+ def Tag(self): # type: (...) -> str
701
+ raise Exception("Not supported when running outside of Excel")
702
+
703
+ @property
704
+ def Context(self): # type: (...) -> typing.Any
705
+ raise Exception("Not supported when running outside of Excel")
706
+
707
+ class CacheKey:
708
+
709
+ def __init__(self):
710
+ raise NotImplementedError()
711
+
712
+ def __hash__(self):
713
+ raise NotImplementedError()
714
+
715
+ def __lt__(self, other):
716
+ raise NotImplementedError()
717
+
718
+ def __le__(self, other):
719
+ raise NotImplementedError()
720
+
721
+ def __gt__(self, other):
722
+ raise NotImplementedError()
723
+
724
+ def __ge__(self, other):
725
+ raise NotImplementedError()
726
+
727
+ def __eq__(self, other):
728
+ raise NotImplementedError()
729
+
730
+ def __ne__(self, other):
731
+ raise NotImplementedError()
732
+
733
+ class CachedValue:
734
+
735
+ def __init__(self):
736
+ raise NotImplementedError()
737
+
738
+ @property
739
+ def value(self):
740
+ raise NotImplementedError()
741
+
742
+ @property
743
+ def exc_info(self):
744
+ raise NotImplementedError()
745
+
746
+ def lru_cache_info(function=None):
747
+ """
748
+ Returns a dictionary of information about the state of the LRU
749
+ cache for a function.
750
+
751
+ If called without a function a dictionary of states is returned
752
+ keyed by the Excel function name.
753
+
754
+ The information dictionary (or dictionaries) contain the following keys:
755
+
756
+ - maxsize
757
+ - currsize
758
+ - hits
759
+ - misses
760
+
761
+ :param function: Function to get information for, or None for all cached functions.
762
+ :return: dict of cache information.
763
+ """
764
+ return {}
765
+
766
+ def lru_cache_clear(function=None):
767
+ """
768
+ Clear one or all LRU caches.
769
+
770
+ :param function: Function to clear LRU cache for, or None for all cached functions.
771
+ """
772
+ return None
773
+
774
+ _pd_pandas = None
775
+ _pd_numpy = None
776
+ def _pandas_get_imports():
777
+ """Convenience function to lazily import pandas and numpy."""
778
+ global _pd_pandas, _pd_numpy
779
+ if _pd_pandas is None:
780
+ import pandas as pandas_module # type: ignore
781
+ _pd_pandas = pandas_module
782
+ if _pd_numpy is None:
783
+ import numpy as numpy_module # type: ignore
784
+ _pd_numpy = numpy_module
785
+ return _pd_pandas, _pd_numpy
786
+
787
+ class ObjectCacheKeyError(KeyError):
788
+ """Key not found in object cache"""
789
+ pass
790
+
791
+ class SpillError(RuntimeError):
792
+ """Exception used when an Excel array doesn't have
793
+ room to expand to the size required."""
794
+ pass
795
+
796
+ class CalcError(RuntimeError):
797
+ """Exception used when setting an async value after the current
798
+ calculation has ended."""
799
+ pass
800
+
801
+ class ThreadKilledError(Exception):
802
+ """Exception used when a background thread needs to be stopped."""
803
+ pass
804
+
805
+ class PropagatedError(Exception):
806
+ """Raised when an error is propagated from one Excel function to another."""
807
+ pass
808
+
809
+ class TypeParameters:
810
+ """Used in conjunction with typing.Annotated to add
811
+ type parameters to type information used by PyXLL.
812
+
813
+ For example::
814
+
815
+ @xl_func
816
+ def sample(df: Annotated[pd.DataFrame, TypeParameters(index=True)]):
817
+ ...
818
+
819
+ Is equivalent to:
820
+
821
+ @xl_func("dataframe<index=True> df")
822
+ def sample(df):
823
+ ...
824
+ """
825
+
826
+ def __init__(self, *args, **kwargs):
827
+ self.args = args
828
+ self.kwargs = kwargs
829
+
830
+ _RTDG_T = typing.TypeVar("_RTDG_T")
831
+
832
+ RTDGenerator = typing.TypeAliasType("RTDGenerator",
833
+ typing.Generator[_RTDG_T, None, None],
834
+ type_params=(_RTDG_T,))
835
+
836
+ AsyncRTDGenerator = typing.TypeAliasType("AsyncRTDGenerator",
837
+ typing.AsyncGenerator[_RTDG_T, None],
838
+ type_params=(_RTDG_T,))
839
+
840
+ _OBJECT_T = typing.TypeVar("_OBJECT_T")
841
+
842
+ Object = typing.TypeAliasType("Object",
843
+ _OBJECT_T,
844
+ type_params=(_OBJECT_T,))
845
+
846
+ class TableBase:
847
+ """
848
+ Base class for writing Tables to Excel.
849
+
850
+ This class can be used as a base class for user defined table classes
851
+ to customize how tables get written to Excel.
852
+
853
+ The ``Table`` class is an implementation of this class.
854
+
855
+ When writing a table to Excel, for example::
856
+
857
+ cell = XLCell.from_range(rng)
858
+ cell.value = Table(..)
859
+
860
+ the following happens:
861
+
862
+ 1. Table.find_table(rng) is called to see if there is an existing ListObject object.
863
+ 2. Table.clear_formatting(list_object) is called.
864
+ 3. If no existing ListObject is found, Table.create_table(rng) is called.
865
+ 4. If the ListObject size is different from that returned by Table.rows() and
866
+ Table.columns(), Table.resize_table(list_object) is called.
867
+ 5. Table.update_table(list_object) is called to update the data in the
868
+ ListObject table object.
869
+ 6. Table.apply_formatting(list_object) is called.
870
+ 7. Finally, Table.apply_filters and Table.apply_sorting are called to (re)apply
871
+ any filtering and sorting to the table.
872
+
873
+ """
874
+
875
+ def __init__(self, data=None, type=None, formatter=None, **kwargs):
876
+ self.__data = data
877
+ self.__type = type
878
+ self.__formatter = formatter
879
+ self.__kwargs = kwargs
880
+
881
+ def com_package(self):
882
+ """Return the ``com_package`` to use when passing COM objects to methods of this class.
883
+ Can be one of `pythoncom`, `win32com`, `comtypes` or `None` to use the default set
884
+ in the pyxll.cfg file.
885
+ """
886
+ return None
887
+
888
+ def find_table(self, xl_range):
889
+ """Finds the ListObject for the table.
890
+ This is called when writing a table to a range to find an existing table
891
+ to update, if there is one.
892
+
893
+ :param xl_range: Range where the table is being written to as a Range COM object.
894
+ :return: ListObject COM object or None if not found.
895
+ """
896
+ raise NotImplementedError()
897
+
898
+ def create_table(self, xl_range):
899
+ """Creates a new ListObject for the table.
900
+ This is called if ``find_table`` returns None.
901
+
902
+ :param xl_range: Range where the table should be placed as a Range COM object.
903
+ :return: ListObject COM object.
904
+ """
905
+ raise NotImplementedError()
906
+
907
+ def rows(self):
908
+ """Return the number of rows in the table, excluding any header row."""
909
+ raise NotImplementedError()
910
+
911
+ def columns(self):
912
+ """Return the number of columns in the table."""
913
+ raise NotImplementedError()
914
+
915
+ def clear_formatting(self, xl_list_object):
916
+ """Clear any formatting before updating the table."""
917
+ raise NotImplementedError()
918
+
919
+ def resize_table(self, xl_list_object, rows, columns):
920
+ """Resizes the ListObject to match the new data.
921
+
922
+ :param xl_list_object: Existing table as a ListObject COM object.
923
+ :param rows: Number of rows to resize the table to (excluding header row).
924
+ :param columns: Number of columns to resize the table to.
925
+
926
+ :return: ListObject COM object.
927
+ """
928
+ raise NotImplementedError()
929
+
930
+ def update_table(self, xl_list_object):
931
+ """Update the ListObject by setting the data on it.
932
+
933
+ :param xl_list_object: Existing table as a ListObject COM object.
934
+ """
935
+ raise NotImplementedError()
936
+
937
+ def apply_formatting(self, xl_list_object):
938
+ """Apply any formatting after updating the table."""
939
+ raise NotImplementedError()
940
+
941
+ def apply_filters(self, xl_list_object):
942
+ """Apply any filters to the table object.
943
+
944
+ :param xl_list_object: Existing table as a ListObject COM object.
945
+ """
946
+ raise NotImplementedError()
947
+
948
+ def apply_sorting(self, xl_list_object):
949
+ """Apply any sorting to the table object.
950
+
951
+ :param xl_list_object: Existing table as a ListObject COM object.
952
+ """
953
+ raise NotImplementedError()
954
+
955
+ def clear_contents(self, xl_list_object):
956
+ """Clears the contents from the Excel table.
957
+
958
+ :param xl_list_object: Existing table as a ListObject COM object.
959
+ """
960
+ raise NotImplementedError()
961
+
962
+ def on_error(self, exc_value, xl_range):
963
+ """
964
+ Called if an error occurs when creating or updating a table.
965
+
966
+ :param exc_value: The exception object raised.
967
+ :param xl_range: The range that was to be used for the table.
968
+ """
969
+ raise NotImplementedError()
970
+
971
+ def reorder_data(self, headers):
972
+ """
973
+ Re-order headers and data to match the existing target tables' headers.
974
+ :param headers: List of existing table's headers
975
+ """
976
+ pass
977
+
978
+ @property
979
+ def skipped_columns(self):
980
+ """List of column indexes (integers) that shouldn't be written to Excel, or None.
981
+
982
+ Can be used in conjunction with reorder_data to prevent column data
983
+ from being written for certain columns.
984
+ """
985
+ return None
986
+
987
+ @property
988
+ def data(self):
989
+ """Data object that was passed to the constructor.
990
+ """
991
+ return self.__data
992
+
993
+ @data.setter
994
+ def data(self, data):
995
+ self.__data = data
996
+
997
+ @property
998
+ def type(self):
999
+ """Data type that was passed to the constructor, including
1000
+ type parameters passed as kwargs.
1001
+
1002
+ The return type should be considered opaque but can be used with
1003
+ pyxll.get_type_converter.
1004
+ """
1005
+ if self.__kwargs:
1006
+ raise NotImplementedError()
1007
+ return self.__type
1008
+
1009
+ @property
1010
+ def formatter(self):
1011
+ """Formatter used to do any cell formatting when writing the table.
1012
+ """
1013
+ return self.__formatter
1014
+
1015
+ @formatter.setter
1016
+ def formatter(self, formatter):
1017
+ self.__formatter = formatter
1018
+
1019
+ class Table(TableBase):
1020
+
1021
+ def __init__(self, data, name=None, type=None, preserve_columns=False, formatter=None, **kwargs):
1022
+ """
1023
+ :param data: DataFrame or other type that can be converted to ``var[][]``.
1024
+ :param name: Table name (optional)
1025
+ :param type: Type signature for `data`. If None, data must be a pandas or polars DataFrame or a list of lists.
1026
+ :param preserve_columns: If true, existing table columns are preserved and no columns are added or removed.
1027
+ :param formatter: Formatter to use for formatting the table.
1028
+ :param kwargs: Additional type parameters.
1029
+ """
1030
+ TableBase.__init__(self, data, type=type, formatter=formatter, **kwargs)
1031
+ self.__name = name
1032
+ self.__type = type
1033
+ self.__kwargs = kwargs
1034
+ self.__preserve_columns = preserve_columns
1035
+ self.__skipped_columns = None
1036
+
1037
+ @property
1038
+ def name(self):
1039
+ """Name of table.
1040
+ Can be fully qualified, eg [Book1]Sheet1!Table1
1041
+ or if None a name will get generated.
1042
+ """
1043
+ return self.__name
1044
+
1045
+ @name.setter
1046
+ def name(self, name):
1047
+ self.__name = name
1048
+
1049
+ @property
1050
+ def preserve_columns(self):
1051
+ """If true, the data will be reordered to match any existing table columns.
1052
+ """
1053
+ return self.__preserve_columns
1054
+
1055
+ @property
1056
+ def skipped_columns(self):
1057
+ """List of column indexes to be skipped after calling reorder_data."""
1058
+ return self.__skipped_columns
1059
+
1060
+ def reorder_data(self, headers):
1061
+ """
1062
+ Re-order headers and data to match the existing target tables' headers.
1063
+ Only used when 'preserve_columns' is True.
1064
+
1065
+ :param headers: List of existing table's headers
1066
+ """
1067
+ raise NotImplementedError()
1068
+
1069
+ def write(self, target):
1070
+ """
1071
+ Find or create a table from the target cell and update it.
1072
+
1073
+ :param target: XLCell or Range instance to write the table to.
1074
+ :return: ListObject
1075
+ """
1076
+ # Implemented in PyXLL add-in
1077
+ raise NotImplementedError()
1078
+
1079
+ def _has_method_override(inst, method_name, base_cls):
1080
+ """Return True if inst.method is different from the base class."""
1081
+ inst_func = getattr(inst, method_name)
1082
+ base_func = getattr(base_cls, method_name)
1083
+ if inst_func == base_func:
1084
+ return False
1085
+
1086
+ try:
1087
+ im_func = getattr(inst_func, "__func__")
1088
+ return im_func != base_func
1089
+ except AttributeError:
1090
+ pass
1091
+
1092
+ return True
1093
+
1094
+ #
1095
+ # API functions / decorators
1096
+ #
1097
+
1098
+ try:
1099
+ if typing.TYPE_CHECKING:
1100
+ from typing import Any, Tuple, Type, Union, Callable
1101
+ from typing import TypeAlias # type: ignore
1102
+
1103
+ try:
1104
+ import exceltypes # type: ignore
1105
+ except ImportError:
1106
+ pass
1107
+ try:
1108
+ import win32com.client # type: ignore
1109
+ except ImportError:
1110
+ pass
1111
+ try:
1112
+ import pythoncom # type: ignore
1113
+ except ImportError:
1114
+ pass
1115
+ try:
1116
+ import comtypes # type: ignore
1117
+ except ImportError:
1118
+ pass
1119
+ try:
1120
+ import types
1121
+ except ImportError:
1122
+ pass
1123
+ try:
1124
+ import configparser
1125
+ except ImportError:
1126
+ pass
1127
+ try:
1128
+ import concurrent
1129
+ except ImportError:
1130
+ pass
1131
+
1132
+ from typing import TypeAlias
1133
+
1134
+ _ExcInfo: TypeAlias = "Tuple[Type[BaseException], BaseException, types.TracebackType]"
1135
+ _OptExcInfo: TypeAlias = "Union[_ExcInfo, Tuple[None, None, None]]"
1136
+ _COMObject: TypeAlias = "Union[win32com.client.Dispatch, pythoncom.PyIUnknown, comtypes.POINTER, Any]"
1137
+ _ExcelApplication: TypeAlias = "Union[exceltypes.Application, _COMObject]"
1138
+ _ExcelRange: TypeAlias = "Union[exceltypes.Range, _COMObject]"
1139
+
1140
+ _P = typing.ParamSpec("_P") # captures parameter types
1141
+ _R = typing.TypeVar("_R") # captures return type
1142
+
1143
+ _Function = typing.TypeVar('_Function', bound=Callable[..., typing.Any])
1144
+ _Decorator = Union[_Function, Callable[[_Function], _Function]]
1145
+
1146
+ except ImportError:
1147
+ pass
1148
+
1149
+ @typing.overload
1150
+ def xl_func(
1151
+ signature, # type: _Function
1152
+ category=None, # type: typing.Union[str, None]
1153
+ help_topic="", # type: str
1154
+ thread_safe=False, # type: bool
1155
+ macro=False, # type: bool
1156
+ allow_abort=None, # type: typing.Union[bool, None]
1157
+ volatile=None, # type: typing.Union[bool, None]
1158
+ disable_function_wizard_calc=None, # type: typing.Union[bool, None]
1159
+ disable_replace_calc=None, # type: typing.Union[bool, None]
1160
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1161
+ name=None, # type: typing.Union[str, None]
1162
+ name_prefix=None, # type: typing.Union[str, None]
1163
+ name_suffix=None, # type: typing.Union[str, None]
1164
+ auto_resize=None, # type: typing.Union[bool, None]
1165
+ hidden=False, # type: bool
1166
+ transpose=False, # type: bool
1167
+ recalc_on_open=None, # type: typing.Union[bool, None]
1168
+ recalc_on_reload=None, # type: typing.Union[bool, None]
1169
+ formatter=None, # type: typing.Union[BaseFormatter, None]
1170
+ async_cache=None, # type: typing.Union[bool, None]
1171
+ nan_value=_no_value,
1172
+ posinf_value=_no_value,
1173
+ neginf_value=_no_value,
1174
+ none_value=_no_value,
1175
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1176
+ lru_cache=None, # type: typing.Union[int, bool, None]
1177
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1178
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1179
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1180
+ ): # type: (...) -> _Function
1181
+ ...
1182
+
1183
+ @typing.overload
1184
+ def xl_func(
1185
+ signature=None, # type: typing.Union[str, None]
1186
+ category=None, # type: typing.Union[str, None]
1187
+ help_topic="", # type: str
1188
+ thread_safe=False, # type: bool
1189
+ macro=False, # type: bool
1190
+ allow_abort=None, # type: typing.Union[bool, None]
1191
+ volatile=None, # type: typing.Union[bool, None]
1192
+ disable_function_wizard_calc=None, # type: typing.Union[bool, None]
1193
+ disable_replace_calc=None, # type: typing.Union[bool, None]
1194
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1195
+ name=None, # type: typing.Union[str, None]
1196
+ name_prefix=None, # type: typing.Union[str, None]
1197
+ name_suffix=None, # type: typing.Union[str, None]
1198
+ auto_resize=None, # type: typing.Union[bool, None]
1199
+ hidden=False, # type: bool
1200
+ transpose=False, # type: bool
1201
+ recalc_on_open=None, # type: typing.Union[bool, None]
1202
+ recalc_on_reload=None, # type: typing.Union[bool, None]
1203
+ formatter=None, # type: typing.Union[BaseFormatter, None]
1204
+ async_cache=None, # type: typing.Union[bool, None]
1205
+ nan_value=_no_value,
1206
+ posinf_value=_no_value,
1207
+ neginf_value=_no_value,
1208
+ none_value=_no_value,
1209
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1210
+ lru_cache=None, # type: typing.Union[int, bool, None]
1211
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1212
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1213
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1214
+ ): # type: (...) -> typing.Callable[[_Function], _Function]
1215
+ ...
1216
+
1217
+ def xl_func(
1218
+ signature=None, # type: typing.Union[str, _Function, None]
1219
+ category=None, # type: typing.Union[str, None]
1220
+ help_topic="", # type: str
1221
+ thread_safe=False, # type: bool
1222
+ macro=False, # type: bool
1223
+ allow_abort=None, # type: typing.Union[bool, None]
1224
+ volatile=None, # type: typing.Union[bool, None]
1225
+ disable_function_wizard_calc=None, # type: typing.Union[bool, None]
1226
+ disable_replace_calc=None, # type: typing.Union[bool, None]
1227
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1228
+ name=None, # type: typing.Union[str, None]
1229
+ name_prefix=None, # type: typing.Union[str, None]
1230
+ name_suffix=None, # type: typing.Union[str, None]
1231
+ auto_resize=None, # type: typing.Union[bool, None]
1232
+ hidden=False, # type: bool
1233
+ transpose=False, # type: bool
1234
+ recalc_on_open=None, # type: typing.Union[bool, None]
1235
+ recalc_on_reload=None, # type: typing.Union[bool, None]
1236
+ formatter=None, # type: typing.Union[BaseFormatter, None]
1237
+ async_cache=None, # type: typing.Union[bool, None]
1238
+ nan_value=_no_value,
1239
+ posinf_value=_no_value,
1240
+ neginf_value=_no_value,
1241
+ none_value=_no_value,
1242
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1243
+ lru_cache=None, # type: typing.Union[int, bool, None]
1244
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1245
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1246
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1247
+ ): # type: (...) -> _Decorator
1248
+ """
1249
+ Decorator for exposing functions to excel, e.g.:
1250
+
1251
+ @xl_func
1252
+ def my_xl_function(a, b, c):
1253
+ '''docstrings appear as helptext in Excel'''
1254
+ return "%s %s %s" % (a, b, c)
1255
+
1256
+ A signature may be provided to give type information for the
1257
+ arguments and return type, e.g.:
1258
+
1259
+ @xl_func("string a, int b, float c: string")
1260
+ def my_xl_function(a, b, c)
1261
+ return "%s %d %f" % (a, b, c)
1262
+
1263
+ Valid types are:
1264
+ str, string, int, bool, float, float[], var or types registered
1265
+ with xl_arg_type.
1266
+
1267
+ The return type is optional, it will default to var.
1268
+
1269
+ Or where available, type hints may be used:
1270
+
1271
+ @xl_func
1272
+ def strlen(x: str) -> int:
1273
+ return len(x)
1274
+
1275
+ """
1276
+ # xl_func may be called with no arguments as a plain decorator, in which
1277
+ # case the first argument will be the function it's applied to.
1278
+ if signature is not None and callable(signature):
1279
+ return signature
1280
+
1281
+ # or it will return a decorator.
1282
+ def dummy_decorator(func):
1283
+ return func
1284
+ return dummy_decorator
1285
+
1286
+ def xl_arg_doc(arg_name, # type: str
1287
+ docstring # type: str
1288
+ ): # type: (...) -> typing.Callable[[_Function], _Function]
1289
+ """
1290
+ Decorator for documenting a function's named parameters.
1291
+ Must be applied before xl_func.
1292
+
1293
+ eg:
1294
+
1295
+ @xl_func("int a, int b: int")
1296
+ @xl_arg_doc("a", "this is the docstring for a")
1297
+ @xl_arg_doc("b", "this is the docstring for b")
1298
+ def my_xl_function(a, b):
1299
+ return a + b
1300
+
1301
+ Alternatively if no docstrings are explicitly supplied
1302
+ and the function has a docstring, PyXLL will try and
1303
+ find parameter documentation in the docstring.
1304
+
1305
+ @xl_func("int a, int b: int")
1306
+ def my_xl_function(a, b):
1307
+ '''
1308
+ return a + b
1309
+
1310
+ a : this is the docstring for a
1311
+ b : this is the docstring for b
1312
+ '''
1313
+ return a + b
1314
+
1315
+ """
1316
+ def dummy_decorator(func):
1317
+ return func
1318
+ return dummy_decorator
1319
+
1320
+ @typing.overload
1321
+ def xl_macro(signature, # type: _Function
1322
+ allow_abort=None, # type: typing.Union[bool, None]
1323
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1324
+ name=None, # type: typing.Union[str, None]
1325
+ name_prefix=None, # type: typing.Union[str, None]
1326
+ name_suffix=None, # type: typing.Union[str, None]
1327
+ shortcut=None, # type: typing.Union[str, None]
1328
+ transpose=False, # type: typing.Union[bool, None]
1329
+ nan_value=_no_value,
1330
+ posinf_value=_no_value,
1331
+ neginf_value=_no_value,
1332
+ none_value=_no_value,
1333
+ disable_calculation=False, # type: bool
1334
+ disable_screen_updating=False, # type: bool
1335
+ disable_alerts=False, # type: bool
1336
+ restore_selection=False, # type: bool
1337
+ restore_active_sheet=False, # type: bool
1338
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1339
+ lru_cache=None, # type: typing.Union[int, bool, None]
1340
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1341
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1342
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1343
+ ): # type: (...) -> _Function
1344
+ ...
1345
+
1346
+ @typing.overload
1347
+ def xl_macro(signature, # type: typing.Union[str, None]
1348
+ allow_abort=None, # type: typing.Union[bool, None]
1349
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1350
+ name=None, # type: typing.Union[str, None]
1351
+ name_prefix=None, # type: typing.Union[str, None]
1352
+ name_suffix=None, # type: typing.Union[str, None]
1353
+ shortcut=None, # type: typing.Union[str, None]
1354
+ transpose=False, # type: typing.Union[bool, None]
1355
+ nan_value=_no_value,
1356
+ posinf_value=_no_value,
1357
+ neginf_value=_no_value,
1358
+ none_value=_no_value,
1359
+ disable_calculation=False, # type: bool
1360
+ disable_screen_updating=False, # type: bool
1361
+ disable_alerts=False, # type: bool
1362
+ restore_selection=False, # type: bool
1363
+ restore_active_sheet=False, # type: bool
1364
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1365
+ lru_cache=None, # type: typing.Union[int, bool, None]
1366
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1367
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1368
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1369
+ ): # type: (...) -> typing.Callable[[_Function], _Function]
1370
+ ...
1371
+
1372
+ def xl_macro(signature=None, # type: typing.Union[str, _Function, None]
1373
+ allow_abort=None, # type: typing.Union[bool, None]
1374
+ arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
1375
+ name=None, # type: typing.Union[str, None]
1376
+ name_prefix=None, # type: typing.Union[str, None]
1377
+ name_suffix=None, # type: typing.Union[str, None]
1378
+ shortcut=None, # type: typing.Union[str, None]
1379
+ transpose=False, # type: typing.Union[bool, None]
1380
+ nan_value=_no_value,
1381
+ posinf_value=_no_value,
1382
+ neginf_value=_no_value,
1383
+ none_value=_no_value,
1384
+ disable_calculation=False, # type: bool
1385
+ disable_screen_updating=False, # type: bool
1386
+ disable_alerts=False, # type: bool
1387
+ restore_selection=False, # type: bool
1388
+ restore_active_sheet=False, # type: bool
1389
+ cache=None, # typing.Union[None, collections.abc.MutableMapping]
1390
+ lru_cache=None, # type: typing.Union[int, bool, None]
1391
+ decimals_to_float=None, # type: typing.Union[int, bool, None]
1392
+ propagate_errors=None, # type: typing.Union[int, bool, typing.Dict[str, bool], None]
1393
+ propagate_errors_filter=None # type: typing.Union[typing.Callable, typing.Dict[str, typing.Callable], None]
1394
+ ): # type: (...) -> _Decorator
1395
+ """
1396
+ Decorator for exposing python functions as macros.
1397
+
1398
+ Macros are used like VBA macros and can be assigned to buttons.
1399
+ They take no arguments the return value is not used.
1400
+
1401
+ Macros may call macro sheet functions and may call back
1402
+ into Excel like menu items.
1403
+
1404
+ eg:
1405
+ @xl_macro
1406
+ def my_macro():
1407
+ win32api.MessageBox(0, "my_macro", "my_macro")
1408
+
1409
+ A signature may be applied to the function, e.g.:
1410
+
1411
+ @xl_macro("string x: int")
1412
+ def strlen(x):
1413
+ return len(x)
1414
+
1415
+ Or where possible, type hints may be used:
1416
+
1417
+ @xl_macro
1418
+ def strlen(x: str) -> int:
1419
+ return len(x)
1420
+
1421
+ """
1422
+ # xl_macro may be called with no arguments as a plain decorator, in which
1423
+ # case the first argument will be the function it's applied to.
1424
+ if signature is not None and callable(signature):
1425
+ return signature
1426
+
1427
+ # or it will return a decorator.
1428
+ def dummy_decorator(func):
1429
+ return func
1430
+ return dummy_decorator
1431
+
1432
+ @typing.overload
1433
+ def xl_menu(
1434
+ name, # type: _Function
1435
+ menu=None, # type: typing.Union[str, None]
1436
+ sub_menu=None, # type: typing.Union[str, None]
1437
+ order=None, # type: typing.Union[int, None]
1438
+ sub_order=None, # type: typing.Union[int, None]
1439
+ menu_order=None, # type: typing.Union[int, None]
1440
+ allow_abort=None, # type: typing.Union[bool, None]
1441
+ shortcut=None # type: typing.Union[str, None]
1442
+ ): # type: (...) -> _Function
1443
+ ...
1444
+
1445
+ @typing.overload
1446
+ def xl_menu(
1447
+ name=None, # type: typing.Union[str, None]
1448
+ menu=None, # type: typing.Union[str, None]
1449
+ sub_menu=None, # type: typing.Union[str, None]
1450
+ order=None, # type: typing.Union[int, None]
1451
+ sub_order=None, # type: typing.Union[int, None]
1452
+ menu_order=None, # type: typing.Union[int, None]
1453
+ allow_abort=None, # type: typing.Union[bool, None]
1454
+ shortcut=None # type: typing.Union[str, None]
1455
+ ): # type: (...) -> typing.Callable[[_Function], _Function]
1456
+ ...
1457
+
1458
+ def xl_menu(name=None, # type: typing.Union[str, _Function, None]
1459
+ menu=None, # type: typing.Union[str, None]
1460
+ sub_menu=None, # type: typing.Union[str, None]
1461
+ order=None, # type: typing.Union[int, None]
1462
+ sub_order=None, # type: typing.Union[int, None]
1463
+ menu_order=None, # type: typing.Union[int, None]
1464
+ allow_abort=None, # type: typing.Union[bool, None]
1465
+ shortcut=None # type: typing.Union[str, None]
1466
+ ): # type: (...) -> _Decorator
1467
+ """
1468
+ Decorator for creating custom menu items.
1469
+
1470
+ e.g.
1471
+
1472
+ @xl_menu("My menu item")
1473
+ def my_menu_item():
1474
+ print "my menu item was called"
1475
+
1476
+ Adds a menu item 'My menu item' to the default menu (PyXLL or addin
1477
+ name).
1478
+
1479
+ @xl_menu("My menu item", menu="My Menu")
1480
+ def my_menu_item():
1481
+ print "my menu item was called"
1482
+
1483
+ Creates a new menu "My Menu" and adds "My menu item" to it.
1484
+
1485
+ @xl_menu("Mysub-menu item", menu="My Menu", sub_menu="My Sub Menu")
1486
+ def my_menu_item():
1487
+ print "my menu item was called"
1488
+
1489
+ Creates a new sub-menu "My Sub Menu" and adds "My sub-menu item"
1490
+ to it.
1491
+ If the menu My Menu didn't already exist, it would create it too.
1492
+ """
1493
+ # xl_menu may be called with no arguments as a plain decorator, in which
1494
+ # case the first argument will be the function it's applied to.
1495
+ if name is not None and callable(name):
1496
+ return name
1497
+
1498
+ # or it will return a decorator.
1499
+ def dummy_decorator(func):
1500
+ return func
1501
+ return dummy_decorator
1502
+
1503
+ def xl_license_notifier(func):
1504
+ # type: (_Function) -> _Function
1505
+ """
1506
+ Decorator for callbacks to notify user code of the current state of
1507
+ the license.
1508
+
1509
+ The decorated function must be of the form:
1510
+ def callback(string name, datetime.date expdate, int days_left)
1511
+
1512
+ All registered callbacks are called when the license is checked at the time
1513
+ pyxll is first loaded, and again each time the license is checked and there
1514
+ has been a change since the last time it was checked.
1515
+ """
1516
+ return func
1517
+
1518
+ def xl_on_close(func):
1519
+ # type: (_Function) -> _Function
1520
+ """
1521
+ Decorator for callbacks that should be called when Excel is about
1522
+ to be closed.
1523
+
1524
+ Even after this function has been called, it's possible Excel won't
1525
+ actually close as the user may veto it.
1526
+
1527
+ The function should take no arguments.
1528
+ """
1529
+ return func
1530
+
1531
+ def xl_on_reload(func):
1532
+ # type: (_Function) -> _Function
1533
+ """
1534
+ Decorator for callbacks that should be called after a reload is
1535
+ attempted.
1536
+
1537
+ The callback takes a list of tuples of three three items:
1538
+ (modulename, module, exc_info)
1539
+
1540
+ When a module has been loaded successfully, exc_info is None.
1541
+ When a module has failed to load, module is None and exc_info
1542
+ is the exception information (exc_type, exc_value, exc_traceback).
1543
+ """
1544
+ return func
1545
+
1546
+ def xl_on_open(func):
1547
+ # type: (_Function) -> _Function
1548
+ """
1549
+ Decorator for callbacks that should be called after PyXLL has
1550
+ been opened and the user modules have been imported.
1551
+
1552
+ The callback takes a list of tuples of three three items:
1553
+ (modulename, module, exc_info)
1554
+
1555
+ When a module has been loaded successfully, exc_info is None.
1556
+ When a module has failed to load, module is None and exc_info
1557
+ is the exception information (exc_type, exc_value, exc_traceback).
1558
+ """
1559
+ return func
1560
+
1561
+ def get_registered_functions(func_type):
1562
+ """
1563
+ Return a list of all functions registered using one of the
1564
+ PyXLL function decorators.
1565
+
1566
+ :param func_type: String identifier for the type of function to return.
1567
+ Must be one of:
1568
+ - xl_func
1569
+ - xl_macro
1570
+ - xl_menu
1571
+ - xl_event
1572
+ - xl_arg_type
1573
+ - xl_return_type
1574
+ - xl_on_open
1575
+ - xl_on_close
1576
+ - xl_on_reload
1577
+ - xl_license_notifier
1578
+
1579
+ :return: list of dicts containing the function (keyed by 'func'), and
1580
+ any non-default kwargs that were passed to the decorator when
1581
+ registering the function.
1582
+
1583
+ For 'xl_func' and 'xl_macro' the dicts also include:
1584
+ - 'signature': a human-readable signature string, e.g.
1585
+ "int a, int b: int". The signature is normalized and incorporates
1586
+ all type information for the function, so may not be identical to
1587
+ the signature string passed to `@xl_func` or `@xl_macro`.
1588
+ - 'arg_types': a list of {'name': ..., 'type': ...} dicts, one
1589
+ per argument (including any '*args'/'**kwargs' argument).
1590
+ If the type was specified only using a type hint this type will
1591
+ be that type hint, otherwise it's a string describing the full
1592
+ type specification.
1593
+ - 'return_type': the function's return type, in the same form
1594
+ as the 'type' values in 'arg_types'.
1595
+ """
1596
+ raise Exception("Not supported when running outside of Excel")
1597
+
1598
+ _async_call_warning_enabled = True
1599
+ def async_call(func, *args, **kwargs):
1600
+ """
1601
+ Schedule a function to be called after the current Excel
1602
+ calculation cycle has completed.
1603
+
1604
+ The function is called in an Excel macro context with automatic
1605
+ calculation disabled, so it is safe to use :py:func:`xl_app` and
1606
+ other COM and macro functions.
1607
+
1608
+ This can be used by worksheet functions that need to modify the worksheet
1609
+ where calling back into Excel would fail or cause a deadlock.
1610
+
1611
+ NOTE: In the stubs version (not embedded in PyXLL) the function
1612
+ is called immediately.
1613
+
1614
+ :param func: Function or callable object to call in an Excel macro context
1615
+ at some time in the near future.
1616
+ """
1617
+ global _async_call_warning_enabled
1618
+ if _async_call_warning_enabled:
1619
+ _log.warning("pyxll.async_call is deprecated and will be removed in a future release. "
1620
+ "Use pyxll.schedule_call instead.")
1621
+ _async_call_warning_enabled = False
1622
+ func(*args, **kwargs)
1623
+
1624
+ def schedule_call(func, # type: _Function
1625
+ *args,
1626
+ delay=0, # type: int
1627
+ nowait=False, # type: bool
1628
+ retries=0, # type: int
1629
+ retry_delay=0.0, # type: float
1630
+ retry_backoff=1.0, # type: float
1631
+ retry_filter=None, # type: typing.Union[typing.Callable[[BaseException], bool], None]
1632
+ disable_calculation=False, # type: bool
1633
+ disable_screen_updating=False, # type: bool
1634
+ disable_alerts=False, # type: bool
1635
+ restore_selection=False, # type: bool
1636
+ restore_active_sheet=False # type: bool
1637
+ ): # type: (...) -> typing.Union[asyncio.futures.Future[Any], None]
1638
+ """
1639
+ Schedule a function to be called after the current Excel
1640
+ calculation cycle has completed.
1641
+
1642
+ The function is called in an Excel macro context with automatic
1643
+ calculation disabled, so it is safe to use :py:func:`xl_app` and
1644
+ other COM and macro functions.
1645
+
1646
+ This can be used by worksheet functions that need to modify the worksheet
1647
+ where calling back into Excel would fail or cause a deadlock.
1648
+
1649
+ From Python 3.7 onwards when called from the PyXLL asyncio event loop and
1650
+ 'nowait' is not set this function returns an asyncio.Future. This future
1651
+ can be awaited on to get the result of the call.
1652
+
1653
+ NOTE: In the stubs version (not embedded in PyXLL) the function
1654
+ is called immediately.
1655
+
1656
+ :param func: Function or callable object to call in an Excel macro context
1657
+ at some time in the near future.
1658
+
1659
+ :param *args: Arguments to be passed to the the function.
1660
+
1661
+ :param delay: Delay in seconds to wait before calling the function.
1662
+
1663
+ :param nowait: Do not return a Future even if called from the asyncio event loop.
1664
+
1665
+ :param retries: Integer number of times to retry.
1666
+
1667
+ :param retry_delay: Time in seconds to wait between retries.
1668
+
1669
+ :param retry_backoff: Multiplier to apply to 'retry_delay' after each retry. This
1670
+ can be used to increase the time between each retry by setting
1671
+ 'retry_backoff' to > 1.0.
1672
+
1673
+ :param retry_filter: Callable that received the exception value in the case of an
1674
+ error. It should return True if a retry should be attempted
1675
+ or False otherwise.
1676
+
1677
+ :param disable_calculation: Disable automatic calculations while the callback is being called.
1678
+ This switches the Excel calculation mode to manual and restores it
1679
+ to its previous mode after the call is complete.
1680
+
1681
+ :param disable_screen_updating: Disable Excel's screen updating while the callback is being called.
1682
+ Screen updating is restored to its previous mode after the call is
1683
+ complete.
1684
+
1685
+ .. warning::
1686
+
1687
+ This function doesn't allow passing keyword arguments to the schedule function.
1688
+ To do that, use functools.partial().::
1689
+
1690
+ # Will schedule "print("Hello", flush=True)"
1691
+ schedule_call(functools.partial(print, "Hello", flush=True))
1692
+ """
1693
+
1694
+ # In the stubs package the function gets called immediately, regardless
1695
+ # of the delay passed in or what thread we might be running in.
1696
+ result = func(*args)
1697
+
1698
+ if not nowait:
1699
+ # Check to see if we are running in an asyncio event loop
1700
+ try:
1701
+ import asyncio
1702
+ loop = asyncio.get_running_loop()
1703
+ except (ImportError, AttributeError, RuntimeError):
1704
+ return None
1705
+
1706
+ # We are so return the result in a Future
1707
+ future = loop.create_future()
1708
+ future.set_result(result)
1709
+ return future
1710
+
1711
+ return None
1712
+
1713
+ # Ribbon
1714
+ _default_ribbon_xml = """<?xml version="1.0" ?>
1715
+ <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" loadImage="pyxll.load_image">
1716
+ <ribbon><tabs/></ribbon>
1717
+ </customUI>
1718
+ """
1719
+
1720
+ def _xml_to_dom(xml):
1721
+ # type: (Union[minidom.Document, str]) -> minidom.Document
1722
+ """Takes xml as a string or dom and returns a document object"""
1723
+ if not isinstance(xml, minidom.Document):
1724
+ return minidom.parseString(xml)
1725
+ return xml
1726
+
1727
+ def _validate_ribbon_xml(xml):
1728
+ """Tests the ribbon xml to make sure it looks reasonable.
1729
+ Returns validated xml as text.
1730
+ """
1731
+
1732
+ # Early out if ribbon validation is disabled
1733
+ cfg = get_config()
1734
+ if cfg.has_option("PYXLL", "disable_ribbon_validation"):
1735
+ cfg_value = cfg.get("PYXLL", "disable_ribbon_validation")
1736
+ try:
1737
+ if bool(int(cfg.get("PYXLL", "disable_ribbon_validation"))):
1738
+ return
1739
+ except (TypeError, ValueError):
1740
+ _log.warning("Unexpected value for 'disable_ribbon_validation' (expected 0 or 1): %s" % cfg_value)
1741
+
1742
+ xml = _xml_to_dom(xml)
1743
+
1744
+ if not xml.documentElement:
1745
+ raise AssertionError("Ribbon XML is missing a root document element")
1746
+
1747
+ if not xml.documentElement.tagName == "customUI":
1748
+ raise AssertionError("Ribbon XML document element is expected to be 'customUI' "
1749
+ "(not '%s'" % xml.documentElement.tagName)
1750
+
1751
+ def _assert_unique_attr(element, attr, error, values={}):
1752
+ elements = [element]
1753
+ while elements:
1754
+ element = elements[0]
1755
+ elements = elements[1:] + list(element.childNodes or [])
1756
+ attributes = element.attributes or {}
1757
+ value = getattr(attributes.get(attr, None), "value", None)
1758
+ if value:
1759
+ if value in values:
1760
+ raise AssertionError(error % {"attr": attr, "value": value})
1761
+ values[value] = None
1762
+
1763
+ _assert_unique_attr(xml.documentElement,
1764
+ "id",
1765
+ "Duplicate %(attr)s attribute '%(value)s' found.")
1766
+
1767
+ def _assert_at_most_one(element, tag_name, error):
1768
+ children = {}
1769
+ for child in element.childNodes:
1770
+ if child.nodeType != child.ELEMENT_NODE:
1771
+ continue
1772
+ children.setdefault(child.tagName, [])
1773
+ children[child.tagName].append(child)
1774
+ tag_children = children.get(tag_name, [])
1775
+ if len(tag_children) > 1:
1776
+ raise AssertionError(error)
1777
+ if tag_children:
1778
+ return tag_children[0]
1779
+
1780
+ ribbon = _assert_at_most_one(xml.documentElement,
1781
+ "ribbon",
1782
+ "'customUI' element in ribbon XML should have a single ribbon node")
1783
+
1784
+ if ribbon:
1785
+ _assert_at_most_one(ribbon,
1786
+ "tabs",
1787
+ "'ribbon' element in ribbon XML should have a single tabs node)")
1788
+
1789
+ def set_ribbon_tab(xml, tab_id=None, reload=True):
1790
+ # type: (Union[str, minidom.Document], Union[str, None], bool) -> None
1791
+ """
1792
+ Sets a tab in the ribbon using an xml fragment.
1793
+
1794
+ :param xml: Ribbon xml as a string containing at least one tab element.
1795
+ :param tab_id: Id of tab to add if multiple tabs exist in the xml.
1796
+ :param reload: If true the ribbon will be refreshed immediately.
1797
+ """
1798
+ xml = _xml_to_dom(xml)
1799
+
1800
+ if tab_id:
1801
+ tab_id = str(tab_id)
1802
+ for new_tab in xml.getElementsByTagName("tab"):
1803
+ if str(new_tab.getAttribute("id")) == tab_id:
1804
+ break
1805
+ else:
1806
+ raise KeyError("Tab '%s' not found" % tab_id)
1807
+ else:
1808
+ new_tabs = xml.getElementsByTagName("tab")
1809
+ if not new_tabs:
1810
+ raise RuntimeError("No 'tab' elements found")
1811
+ new_tab = new_tabs[0]
1812
+ tab_id = str(new_tab.getAttribute("id") or "")
1813
+
1814
+ new_xml = get_ribbon_xml(join_merged_attrs=False) # type: Union[minidom.Document, str]
1815
+ if not new_xml:
1816
+ new_xml = _default_ribbon_xml
1817
+ new_xml = _xml_to_dom(new_xml)
1818
+
1819
+ tabs = new_xml.getElementsByTagName("tabs")
1820
+ if tabs:
1821
+ tabs = tabs[0] # type: ignore
1822
+ else:
1823
+ ribbons = new_xml.getElementsByTagName("ribbon")
1824
+ if ribbons:
1825
+ ribbon = ribbons[0] # type: ignore
1826
+ else:
1827
+ ribbon = new_xml.createElement("ribbon") # type: ignore
1828
+ if new_xml.documentElement is None:
1829
+ raise RuntimeError("Document element missing")
1830
+ new_xml.documentElement.appendChild(ribbon)
1831
+ tabs = new_xml.createElement("tabs") # type: ignore
1832
+ ribbon.appendChild(tabs) # type: ignore
1833
+
1834
+ if tab_id:
1835
+ for tab in tabs.childNodes: # type: ignore
1836
+ if tab.nodeType == tab.ELEMENT_NODE \
1837
+ and str(tab.tagName) == "tab" \
1838
+ and str(tab.getAttribute("id")) == tab_id:
1839
+ tabs.replaceChild(new_tab, tab) # type: ignore
1840
+ break
1841
+ else:
1842
+ tabs.appendChild(new_tab) # type: ignore
1843
+ else:
1844
+ tabs.appendChild(new_tab) # type: ignore
1845
+
1846
+ set_ribbon_xml(new_xml, reload=reload, keep_merged_attrs=True)
1847
+
1848
+ def remove_ribbon_tab(tab_id, reload=True):
1849
+ # type: (str, bool) -> bool
1850
+ """
1851
+ Removes a tab previously added to the ribbon.
1852
+
1853
+ :param tab_id: Id of tab to remove
1854
+ :param reload: If true the ribbon will be refreshed immediately.
1855
+ :return: True if a tab was removed, False otherwise.
1856
+ """
1857
+ new_xml = get_ribbon_xml(join_merged_attrs=False)
1858
+ if not new_xml:
1859
+ return False
1860
+
1861
+ new_xml = minidom.parseString(new_xml) # type: ignore
1862
+ tabs = new_xml.getElementsByTagName("tab") # type: ignore
1863
+ if not tabs:
1864
+ return False
1865
+
1866
+ updated = False
1867
+ tab_id = str(tab_id)
1868
+ for tab in tabs:
1869
+ if str(tab.getAttribute("id")) == tab_id:
1870
+ tab.parentNode.removeChild(tab)
1871
+ updated = True
1872
+
1873
+ if not updated:
1874
+ return False
1875
+
1876
+ set_ribbon_xml(new_xml, reload=reload, keep_merged_attrs=True)
1877
+ return updated
1878
+
1879
+ _ribbon_xml = ""
1880
+
1881
+ def load_image(filename):
1882
+ # type: (str) -> _COMObject
1883
+ """
1884
+ Loads an image file and returns it as a COM IPicture object suitable for use when
1885
+ customizing the ribbon.
1886
+
1887
+ This function can be set at the Ribbon image handler by setting the loadImage attribute on
1888
+ the customUI element in the ribbon XML file.
1889
+
1890
+ .. code-block:: xml
1891
+ :emphasize-lines: 2, 11
1892
+
1893
+ <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui"
1894
+ loadImage="pyxll.load_image">
1895
+ <ribbon>
1896
+ <tabs>
1897
+ <tab id="CustomTab" label="Custom Tab">
1898
+ <group id="Tools" label="Tools">
1899
+ <button id="Reload"
1900
+ size="large"
1901
+ label="Reload PyXLL"
1902
+ onAction="pyxll.reload"
1903
+ image="reload.png"/>
1904
+ </group>
1905
+ </tab>
1906
+ </tabs>
1907
+ </ribbon>
1908
+ </customUI>
1909
+
1910
+ Or it can be used when returning an image from a getImage callback.
1911
+
1912
+ :param string filename: Filename of the image file to load. This may be an absolute path or relative to
1913
+ the ribbon XML file.
1914
+
1915
+ :return: A COM IPicture object (the exact type depends
1916
+ on the com_package setting in the config file.
1917
+ """
1918
+ raise Exception("Not supported when running outside of Excel")
1919
+
1920
+ def get_ribbon_xml(join_merged_attrs=True):
1921
+ # type: (bool) -> str
1922
+ """Returns the ribbon XML currenly in use by PyXLL."""
1923
+ return _ribbon_xml
1924
+
1925
+ def set_ribbon_xml(xml, reload=True, keep_merged_attrs=False):
1926
+ # type: (typing.Union[str, minidom.Document], bool, bool) -> None
1927
+ """
1928
+ Sets the XML used by PyXLL for customizing the ribbon.
1929
+
1930
+ :param xml: XML document to set as the current ribbon
1931
+ :param reload: If true the ribbon will be refreshed immediately.
1932
+ """
1933
+
1934
+ _validate_ribbon_xml(xml)
1935
+
1936
+ if _have_minidom:
1937
+ if isinstance(xml, minidom.Document):
1938
+ xml = xml.toxml()
1939
+
1940
+ global _ribbon_xml
1941
+ _ribbon_xml = xml # type: ignore
1942
+
1943
+ def get_ribbon_ui():
1944
+ # type: () -> _COMObject
1945
+ """Returns the Ribbon COM object.
1946
+ """
1947
+ raise Exception("Not supported when running outside of Excel")
1948
+
1949
+ class ErrorContext:
1950
+ """Context object passed to the PyXLL error handler."""
1951
+
1952
+ class Type:
1953
+ """Type to indicate the origination of the error."""
1954
+ UDF = "udf"
1955
+ MACRO = "macro"
1956
+ MENU = "menu"
1957
+ RIBBON = "ribbon"
1958
+ IMPORT = "import"
1959
+
1960
+ def __init__(self, error_type, function_name=None, import_errors=None):
1961
+ self.error_type = error_type
1962
+ self.function_name = function_name
1963
+ self.import_errors = import_errors
1964
+
1965
+ def _propagated_error_handler(context, exc_type, exc_value, exc_traceback):
1966
+ msg = None
1967
+ args = getattr(exc_value, "args", None)
1968
+ if isinstance(args, (list, tuple)) and len(args) > 0:
1969
+ value = args[0]
1970
+ if isinstance(value, LookupError):
1971
+ msg = "#NULL!"
1972
+ elif isinstance(value, ZeroDivisionError):
1973
+ msg = "#DIV/0!"
1974
+ elif isinstance(value, ValueError):
1975
+ msg = "#VALUE!"
1976
+ elif isinstance(value, ReferenceError):
1977
+ msg = "#REF!"
1978
+ elif isinstance(value, NameError):
1979
+ msg = "#NAME!"
1980
+ elif isinstance(value, ArithmeticError):
1981
+ msg = "#NUM!"
1982
+ elif isinstance(value, RuntimeError):
1983
+ msg = "#N/A"
1984
+
1985
+ if msg is None:
1986
+ # Get the message part from the previous error string.
1987
+ # This assumes the default error handler is being used.
1988
+ msg = str(exc_value)
1989
+ while True:
1990
+ match = re.match(r"^##[A-Z_][A-Z0-9_\.]*:\s*(.*)$", msg, re.IGNORECASE)
1991
+ if not match:
1992
+ break
1993
+ msg = match.group(1).strip()
1994
+
1995
+ error = "##PropagatedError"
1996
+ if msg:
1997
+ error += ": " + msg
1998
+
1999
+ # Truncate long errors to avoid conversion problems
2000
+ if len(error) > 254:
2001
+ return error[:251] + "..."
2002
+
2003
+ return error
2004
+
2005
+ def error_handler(context, exc_type, exc_value, exc_traceback):
2006
+ """Standard PyXLL error handler."""
2007
+ # For UDFs return a preview of the error as a single line
2008
+ if context.error_type in (ErrorContext.Type.UDF, ErrorContext.Type.MACRO):
2009
+ if issubclass(exc_type, PropagatedError):
2010
+ return _propagated_error_handler(context, exc_type, exc_value, exc_traceback)
2011
+
2012
+ error = "##" + getattr(exc_type, "__name__", "Error")
2013
+ msg = str(exc_value)
2014
+
2015
+ # Don't keep nesting errors if they're the same (eg ##ObjectCacheKeyError...)
2016
+ unquoted_msg = msg.strip()
2017
+ while len(unquoted_msg) > 1 and unquoted_msg[0] == unquoted_msg[-1] and unquoted_msg[0] in "\"'":
2018
+ unquoted_msg = unquoted_msg[1:-1]
2019
+ if unquoted_msg.startswith(error):
2020
+ return unquoted_msg
2021
+
2022
+ if msg:
2023
+ error += ": " + msg
2024
+
2025
+ # Truncate long errors to avoid conversion problems
2026
+ if len(error) > 254:
2027
+ return error[:251] + "..."
2028
+
2029
+ return error
2030
+
2031
+ # For menus and ribbon functions display an error message.
2032
+ if context.error_type in (ErrorContext.Type.MENU, ErrorContext.Type.RIBBON):
2033
+ message = ""
2034
+ if context.function_name:
2035
+ message = "Error calling '%s'\n\n" % context.function_name
2036
+ elif context.error_type == ErrorContext.Type.RIBBON:
2037
+ message = "PyXLL Ribbon Error\n\n"
2038
+ exc_type_name = getattr(exc_type, "__name__", "Exception")
2039
+ message += str(exc_type_name) + (str(exc_value) and (": " + str(exc_value)) or "") + "\n\n"
2040
+
2041
+ exc_instance = exc_value
2042
+ if not isinstance(exc_instance, BaseException):
2043
+ try:
2044
+ exc_instance = exc_type(exc_value)
2045
+ except:
2046
+ exc_instance = None
2047
+
2048
+ message += "".join(traceback.format_exception(exc_type, exc_instance, exc_traceback))
2049
+ caption = "PyXLL: " + ((context.error_type == ErrorContext.Type.MENU and "Menu") or "Ribbon") + " Error"
2050
+ # MB_SETFOREGROUND | MB_ICONHAND | MB_HELP
2051
+ message_box(message, caption, 0x00010000 | 0x00000010 | 0x00004000)
2052
+ return
2053
+
2054
+ if context.error_type == ErrorContext.Type.IMPORT:
2055
+ lines = ["Error importing Python modules"]
2056
+ if context.import_errors:
2057
+ lines.append("")
2058
+ for modulename, exc_info in context.import_errors:
2059
+ exc_type, exc_value, exc_traceback = exc_info
2060
+ lines.append("Error importing '%s': %s" % (modulename, exc_value))
2061
+ message = "\n".join(lines)
2062
+ # MB_SETFOREGROUND | MB_ICONHAND | MB_HELP
2063
+ message_box(message, "PyXLL: Error importing Python modules", 0x00010000 | 0x00000010 | 0x00004000)
2064
+ return
2065
+
2066
+ def error_handler_quiet(context, exc_type, exc_value, exc_traceback):
2067
+ """PyXLL error handler that doesn't display any error dialogs"""
2068
+ # For UDFs return a preview of the error as a single line
2069
+ if context.error_type in (ErrorContext.Type.UDF, ErrorContext.Type.MACRO):
2070
+ if issubclass(exc_type, PropagatedError):
2071
+ return _propagated_error_handler(context, exc_type, exc_value, exc_traceback)
2072
+
2073
+ error = "##" + getattr(exc_type, "__name__", "Error")
2074
+ msg = str(exc_value)
2075
+ if msg:
2076
+ error += ": " + msg
2077
+ return error
2078
+
2079
+ # for backwards compatibility with older pyxll.cfg files
2080
+ error_to_string = error_handler
2081
+
2082
+ def _wrap_iunknown(unk, no_dynamic_dispatch=False):
2083
+ """Wrap a pythoncom PyIUnknown object into a win32com.Dispatch"""
2084
+ # Get the PyIDispatch object
2085
+ import pythoncom # type: ignore
2086
+ disp = unk.QueryInterface(pythoncom.IID_IDispatch)
2087
+
2088
+ # Try to wrap using the existing wrapper classes (or generate them if
2089
+ # they don't exist)
2090
+ try:
2091
+ from win32com.client.gencache import EnsureDispatch # type: ignore
2092
+ return EnsureDispatch(disp, bForDemand=0)
2093
+ except:
2094
+ if no_dynamic_dispatch:
2095
+ raise
2096
+ pass
2097
+
2098
+ # If we can't use a generated wrapper then use a dynamic Dispatch wrapper.
2099
+ # This will work but won't add constants to win32com.client.constants.
2100
+ import win32com # type: ignore
2101
+ _log.warning("win32com.client.Dispatch failed. win32com.client.dynamic.Dispatch will be used instead.")
2102
+ _log.warning("Delete your gen_py folder '%s' as it may have become corrupted" % win32com.__gen_path__)
2103
+ from win32com.client.dynamic import Dispatch as DynamicDispatch # type: ignore
2104
+ return DynamicDispatch(disp)
2105
+
2106
+ def _get_iunknown_package(unk):
2107
+ """Return the com package the object is most likely to be from"""
2108
+ try:
2109
+ package = unk.__class__.__module__.split(".", 1)[0]
2110
+ if package in ("comtypes", "xlwings"):
2111
+ return package
2112
+ except AttributeError:
2113
+ pass
2114
+
2115
+ if hasattr(unk, "_oleobj_"):
2116
+ return "win32com"
2117
+
2118
+ return "pythoncom"
2119
+
2120
+ # Formatters
2121
+
2122
+ class BaseFormatter(object):
2123
+ """Base class used for formatting Excel ranges.
2124
+ """
2125
+ def __init__(self, clear=True):
2126
+ self.__clear = clear
2127
+ self.__cached_type_descriptors = {}
2128
+ self.__cached_inner_types = {}
2129
+
2130
+ @classmethod
2131
+ def __get_numpy(cls):
2132
+ try:
2133
+ return cls.__np
2134
+ except AttributeError:
2135
+ try:
2136
+ import numpy # type: ignore
2137
+ cls.__np = numpy
2138
+ except ImportError:
2139
+ cls.__np = None
2140
+ return cls.__np
2141
+
2142
+ @classmethod
2143
+ def __is_sequence(cls, x):
2144
+ np = cls.__get_numpy()
2145
+ if np:
2146
+ return isinstance(x, (list, tuple, np.ndarray))
2147
+ return isinstance(x, (list, tuple))
2148
+
2149
+ @classmethod
2150
+ def __resize_array(cls, value, cell, datatype, datatype_ndim, transpose):
2151
+ # If the data type is object, and it's not an array, don't check if the object
2152
+ # is a sequence just convert it to a 1x1 array.
2153
+ if datatype == "object" and datatype_ndim == 0:
2154
+ value = [[value]]
2155
+
2156
+ # If the data type is a 1d array convert it to 1xN row array
2157
+ if datatype_ndim == 1:
2158
+ value = [value]
2159
+
2160
+ # Make sure the value is a 2d array
2161
+ if not cls.__is_sequence(value):
2162
+ value = [value]
2163
+ if len(value) == 0:
2164
+ value = [[None]]
2165
+ if not cls.__is_sequence(value[0]):
2166
+ value = [value]
2167
+
2168
+ # Transpose the array before matching it to the cell range
2169
+ if transpose:
2170
+ value = list(zip(*value))
2171
+
2172
+ # Pad or trim the array to match the cell range
2173
+ num_rows = cell.rows
2174
+ num_cols = cell.columns
2175
+ new_value = [None] * num_rows
2176
+ for r in range(num_rows):
2177
+ row = []
2178
+ if r < len(value):
2179
+ row = value[r]
2180
+ if len(row) > num_cols:
2181
+ row = row[:num_cols]
2182
+ if len(row) < num_cols:
2183
+ row = list(row) + ([None] * (num_cols - len(row)))
2184
+ new_value[r] = row
2185
+
2186
+ return new_value
2187
+
2188
+ def _get_inner_type_descriptors(self, datatype=None, datatype_ndim=0, datatype_kwargs={}):
2189
+ """Return the inner TypeDescriptors for meta-types, like optional and union.
2190
+
2191
+ If the datatype is an optional or union type, return a list of inner TypeDescriptors
2192
+ in the order they appear in the type descriptor from left to right.
2193
+
2194
+ This is a recursive function that returns the ultimate inner types for nested meta-types.
2195
+
2196
+ If the datatype is not an optional or union type, return None.
2197
+ """
2198
+ if datatype is None or datatype_ndim != 0:
2199
+ return None
2200
+
2201
+ type_desc = datatype
2202
+ if not isinstance(type_desc, TypeDescriptor):
2203
+ try:
2204
+ type_desc = self.__cached_type_descriptors[datatype]
2205
+ except KeyError:
2206
+ type_desc = TypeDescriptor.create(datatype)
2207
+ self.__cached_type_descriptors[datatype] = type_desc
2208
+
2209
+ if type_desc.name not in ("optional", "union"):
2210
+ return None
2211
+
2212
+ if datatype_kwargs:
2213
+ type_desc = type_desc.clone(kwargs=datatype_kwargs)
2214
+
2215
+ type_desc_str = str(type_desc)
2216
+ try:
2217
+ return self.__cached_inner_types[type_desc_str]
2218
+ except KeyError:
2219
+ pass
2220
+
2221
+ if type_desc.name == "optional":
2222
+ dtype = type_desc.kwargs.get("T", None)
2223
+ if dtype is None and type_desc.args:
2224
+ dtype = type_desc.args[0]
2225
+
2226
+ if dtype is None:
2227
+ return None
2228
+
2229
+ if not isinstance(dtype, TypeDescriptor):
2230
+ dtype = TypeDescriptor.create(dtype)
2231
+
2232
+ inner_dtypes = self._get_inner_type_descriptors(dtype)
2233
+ if inner_dtypes is None:
2234
+ inner_dtypes = [dtype]
2235
+
2236
+ self.__cached_inner_types[type_desc_str] = inner_dtypes
2237
+ return inner_dtypes
2238
+
2239
+ elif type_desc.name == "union":
2240
+ dtypes = []
2241
+ for dtype in type_desc.args:
2242
+ if not isinstance(dtype, TypeDescriptor):
2243
+ dtype = TypeDescriptor.create(dtype)
2244
+
2245
+ inner_dtypes = self._get_inner_type_descriptors(dtype)
2246
+ if inner_dtypes is None:
2247
+ inner_dtypes = [dtype]
2248
+
2249
+ dtypes.extend(inner_dtypes)
2250
+
2251
+ self.__cached_inner_types[type_desc_str] = dtypes
2252
+ return dtypes
2253
+
2254
+ return None
2255
+
2256
+ def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
2257
+ """Apply formatting to a cell or range of cells.
2258
+
2259
+ :param cell: XLCell instance to by formatted.
2260
+ :param value: Value being set on the cell(s).
2261
+ :param datatype: Data-type as specified as the return type when using @xl_func.
2262
+ :param datatype_ndim: Number of dimensions if the datatype is an array.
2263
+ :param datatype_kwargs: Data-type keyword arguments.
2264
+ :param transpose: True if the value should be transposed before styling.
2265
+ """
2266
+ if _has_method_override(self, "apply_cell", BaseFormatter):
2267
+ value = self.__resize_array(value, cell, datatype, datatype_ndim, transpose)
2268
+ for i, row_value in enumerate(value):
2269
+ for j, cell_value in enumerate(row_value):
2270
+ self.apply_cell(cell.cell(i, j),
2271
+ cell_value,
2272
+ datatype=datatype,
2273
+ datatype_kwargs=datatype_kwargs)
2274
+
2275
+ def apply_cell(self, cell, value=None, datatype=None, datatype_kwargs={}):
2276
+ """Called for each cell to apply any formatting.
2277
+
2278
+ For most Formatter classes this is the only method that needs to
2279
+ be overridden.
2280
+
2281
+ :param cell: XLCell instance to by formatted.
2282
+ :param value: Value being set on the cell(s).
2283
+ :param datatype: Data-type as specified as the return type when using @xl_func.
2284
+ :param datatype_kwargs: Data-type keyword arguments.
2285
+ """
2286
+ pass
2287
+
2288
+ def clear(self, cell):
2289
+ """Clears any formatting from a cell or range of cells."""
2290
+ if self.__clear:
2291
+ r = cell.to_range()
2292
+ r.Style = "Normal"
2293
+ return self.__clear
2294
+
2295
+ def apply_if_nested(self):
2296
+ """Return True if formatter is to be applied when the function appears inside a nested formula.
2297
+ If True and the formatter is applied to a nested function, the methods clear_nested and apply_nested
2298
+ will be called.
2299
+ """
2300
+ return False
2301
+
2302
+ def apply_nested(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
2303
+ """Apply formatting to a cell or range of cells.
2304
+
2305
+ Used when the formatting is being applied from a nested function and
2306
+ self.apply_if_nested() returned True.
2307
+
2308
+ :param cell: XLCell instance to by formatted.
2309
+ :param value: Value being set on the cell(s).
2310
+ :param datatype: Data-type as specified as the return type when using @xl_func.
2311
+ :param datatype_ndim: Number of dimensions if the datatype is an array.
2312
+ :param datatype_kwargs: Data-type keyword arguments.
2313
+ :param transpose: True if the value should be transposed before styling.
2314
+ """
2315
+ return self.apply(cell,
2316
+ value=value,
2317
+ datatype=datatype,
2318
+ datatype_ndim=datatype_ndim,
2319
+ datatype_kwargs=datatype_kwargs,
2320
+ transpose=transpose)
2321
+
2322
+ def clear_nested(self, cell):
2323
+ """Clears any formatting from a cell or range of cells.
2324
+
2325
+ Used when the formatting is being applied from a nested function and
2326
+ self.apply_if_nested() returned True.
2327
+ """
2328
+ return self.clear(cell)
2329
+
2330
+ @staticmethod
2331
+ def rgb(red, green, blue):
2332
+ """Return a color number from RGB values.
2333
+ Note Excel uses 'BGR' instead of the more usual RGB.
2334
+ """
2335
+ return (red & 0xff) | ((green & 0xff) << 8) | ((blue & 0xff) << 16)
2336
+
2337
+ @staticmethod
2338
+ def apply_styles(cells, styles):
2339
+ """Apply a formatting style dictionaries to list of cells."""
2340
+ for cell, style in zip(cells, styles):
2341
+ BaseFormatter.apply_style(cell, style)
2342
+
2343
+ @staticmethod
2344
+ def apply_style(cell, style):
2345
+ """Apply a formatting style dictionary to a cell."""
2346
+ if not style:
2347
+ return
2348
+
2349
+ r = cell.to_range()
2350
+ interior_color = style.get("interior_color", None)
2351
+ if interior_color is not None:
2352
+ r.Interior.Color = interior_color
2353
+
2354
+ text_color = style.get("text_color", None)
2355
+ if text_color is not None:
2356
+ r.Font.Color = text_color
2357
+
2358
+ bold = style.get("bold", None)
2359
+ if bold is not None:
2360
+ r.Font.Bold = bold
2361
+
2362
+ italic = style.get("italic", None)
2363
+ if italic is not None:
2364
+ r.Font.Italic = italic
2365
+
2366
+ font_size = style.get("font_size", None)
2367
+ if font_size is not None:
2368
+ r.Font.Size = font_size
2369
+
2370
+ number_format = style.get("number_format", None)
2371
+ if number_format is not None:
2372
+ r.NumberFormat = number_format
2373
+
2374
+ auto_fit = style.get("auto_fit", False)
2375
+ if auto_fit:
2376
+ r.AutoFit()
2377
+
2378
+ class FormatterCollection(BaseFormatter):
2379
+
2380
+ def __init__(self, formatters=[]):
2381
+ self.__formatters = formatters
2382
+
2383
+ def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
2384
+ for formatter in self.__formatters:
2385
+ formatter.apply(cell,
2386
+ value,
2387
+ datatype=datatype,
2388
+ datatype_ndim=datatype_ndim,
2389
+ datatype_kwargs=datatype_kwargs,
2390
+ transpose=transpose)
2391
+
2392
+ def clear(self, cell):
2393
+ # Only call clear once unless implemented differently from the base class.
2394
+ # BaseFormatter.clear returns True if the range was cleared.
2395
+ cleared = False
2396
+ for formatter in self.__formatters:
2397
+ has_clear_override = _has_method_override(formatter, "clear", BaseFormatter)
2398
+ if not cleared or has_clear_override:
2399
+ result = formatter.clear(cell)
2400
+ if not has_clear_override and result:
2401
+ cleared = True
2402
+
2403
+ def clear_nested(self, *args, **kwargs):
2404
+ # Only call clear once unless implemented differently from the base class.
2405
+ # BaseFormatter.clear returns True if the range was cleared.
2406
+ cleared = False
2407
+ for formatter in self.__formatters:
2408
+ if formatter.apply_if_nested():
2409
+ has_clear_override = _has_method_override(formatter, "clear", BaseFormatter)
2410
+ if not cleared or has_clear_override:
2411
+ result = formatter.clear(*args, **kwargs)
2412
+ if not has_clear_override and result:
2413
+ cleared = True
2414
+
2415
+ def apply_if_nested(self):
2416
+ for formatter in self.__formatters:
2417
+ if formatter.apply_if_nested():
2418
+ return True
2419
+ return False
2420
+
2421
+ def apply_nested(self, *args, **kwargs):
2422
+ for formatter in self.__formatters:
2423
+ if formatter.apply_if_nested():
2424
+ formatter.apply(*args, **kwargs)
2425
+
2426
+ def __add__(self, other):
2427
+ if isinstance(other, dict):
2428
+ other = Formatter(**other)
2429
+ if not isinstance(other, BaseFormatter):
2430
+ raise TypeError("Can't add non-formatter object to a formatter.")
2431
+ return FormatterCollection(self.__formatters + [other])
2432
+
2433
+ def __iadd__(self, other):
2434
+ if isinstance(other, dict):
2435
+ other = Formatter(**other)
2436
+ if not isinstance(other, BaseFormatter):
2437
+ raise TypeError("Can't add non-formatter object to a formatter.")
2438
+ self.__formatters.append(other)
2439
+ return self
2440
+
2441
+ class Formatter(BaseFormatter):
2442
+ """Formatter for formatting values returned via xl_func, or using XLCell.options.
2443
+
2444
+ Use Formatter.rgb(red, green, blue) for constructing color values.
2445
+
2446
+ Formatters may be combined by adding them together.
2447
+
2448
+ :param interior_color: Value to set the interior color to.
2449
+ :param text_color: Value to set the text color to.
2450
+ :param bold: If true, sent the text style to bold.
2451
+ :param italic: If true, sent the text style to italic.
2452
+ :param font_size: Value to set the font size to.
2453
+ :param number_format: Excel number format to use.
2454
+ :param auto_fit: Auto-fit to the content of the cells. May be True (fit column width),
2455
+ False (don't fit), 'columns' (fit column width), 'rows' (fit row width),
2456
+ 'both' (fit column and row width).
2457
+ """
2458
+
2459
+ def __init__(self,
2460
+ interior_color=None,
2461
+ text_color=None,
2462
+ bold=None,
2463
+ italic=None,
2464
+ font_size=None,
2465
+ number_format=None,
2466
+ auto_fit=None,
2467
+ clear=True):
2468
+ BaseFormatter.__init__(self, clear=clear)
2469
+ self.__style = {}
2470
+ if interior_color is not None:
2471
+ self.__style["interior_color"] = interior_color
2472
+ if text_color is not None:
2473
+ self.__style["text_color"] = text_color
2474
+ if bold is not None:
2475
+ self.__style["bold"] = bold
2476
+ if italic is not None:
2477
+ self.__style["italic"] = italic
2478
+ if font_size is not None:
2479
+ self.__style["font_size"] = font_size
2480
+ if number_format is not None:
2481
+ self.__style["number_format"] = number_format
2482
+ if auto_fit is not None:
2483
+ self.__style["auto_fit"] = auto_fit
2484
+
2485
+ def __add__(self, other):
2486
+ if type(self) == type(other) == Formatter:
2487
+ style = dict(self.__style)
2488
+ style.update(other.__style)
2489
+ return Formatter(**style)
2490
+ elif isinstance(other, dict):
2491
+ return self + Formatter(**other)
2492
+ elif not isinstance(other, BaseFormatter):
2493
+ raise TypeError("Can't add non-formatter object to a formatter.")
2494
+ return FormatterCollection([self, other])
2495
+
2496
+ def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
2497
+ # Update the style to the range
2498
+ self.apply_style(cell, self.__style)
2499
+
2500
+ # Apply any styles from the base class (this handles calling apply_cell if necessary
2501
+ # and so should be done after applying the main style to the whold range).
2502
+ BaseFormatter.apply(self,
2503
+ cell,
2504
+ value,
2505
+ datatype=datatype,
2506
+ datatype_ndim=datatype_ndim,
2507
+ datatype_kwargs=datatype_kwargs,
2508
+ transpose=transpose)
2509
+
2510
+ class DateFormatter(Formatter):
2511
+ """Formatter for dates, times and datetimes.
2512
+
2513
+ All formats are in the standard Python datetime format.
2514
+
2515
+ This formatter tests the values and applies the relevant
2516
+ number format according to the type.
2517
+
2518
+ :param date_format: Format used for date values.
2519
+ :param time_format: Format used for time values.
2520
+ :param datetime_format: Format used for datetime values.
2521
+ """
2522
+
2523
+ def __init__(self,
2524
+ date_format="%Y-%m-%d",
2525
+ time_format="%H:%M:%S",
2526
+ datetime_format=None,
2527
+ **kwargs):
2528
+ Formatter.__init__(self, **kwargs)
2529
+
2530
+ # Convert the Python date format to an Excel number format
2531
+ if not datetime_format:
2532
+ datetime_format = "%s %s" % (date_format, time_format)
2533
+ self.__date_number_format = self.__to_number_format(date_format)
2534
+ self.__time_number_formmat = self.__to_number_format(time_format)
2535
+ self.__datetimetime_number_formmat = self.__to_number_format(datetime_format)
2536
+
2537
+ @staticmethod
2538
+ def __to_number_format(date_format):
2539
+ """Convert a Python date format to an Excel number format."""
2540
+ number_format = date_format.replace("%Y", "yyyy")
2541
+ number_format = number_format.replace("%y", "yy")
2542
+ number_format = number_format.replace("%m", "mm")
2543
+ number_format = number_format.replace("%b", "mmm")
2544
+ number_format = number_format.replace("%d", "dd")
2545
+ number_format = number_format.replace("%H", "hh")
2546
+ number_format = number_format.replace("%M", "mm")
2547
+ number_format = number_format.replace("%S", "ss")
2548
+ return number_format
2549
+
2550
+ def apply_cell(self, cell, value=None, datatype=None, datatype_kwargs={}):
2551
+ """Apply the relevant formatting."""
2552
+ # Inspect the value type first to avoid duplicating these tests
2553
+ is_datetime = isinstance(value, datetime.datetime)
2554
+ has_date = is_datetime or isinstance(value, datetime.date)
2555
+ has_time = is_datetime or isinstance(value, datetime.time)
2556
+
2557
+ # Extract the relevant inner type from optional or union types
2558
+ inner_dtypes = self._get_inner_type_descriptors(datatype, datatype_kwargs=datatype_kwargs)
2559
+ if inner_dtypes:
2560
+ for inner_dtype in inner_dtypes:
2561
+ if is_datetime and "datetime" in inner_dtype.return_base_type_names:
2562
+ datatype = "datetime"
2563
+ break
2564
+ elif has_date and "date" in inner_dtype.return_base_type_names:
2565
+ datatype = "date"
2566
+ break
2567
+ elif has_time and "time" in inner_dtype.return_base_type_names:
2568
+ datatype = "time"
2569
+ break
2570
+
2571
+ # If our datatype is not a datetime type, try to guess it from the value
2572
+ if datatype not in ("datetime", "date", "time"):
2573
+ if is_datetime:
2574
+ datatype = "datetime"
2575
+ elif has_date:
2576
+ datatype = "date"
2577
+ elif has_time:
2578
+ datatype = "time"
2579
+
2580
+ number_format = None
2581
+ if datatype == "datetime":
2582
+ number_format = self.__datetimetime_number_formmat
2583
+ elif datatype == "date":
2584
+ number_format = self.__date_number_format
2585
+ elif datatype == "time":
2586
+ number_format = self.__time_number_formmat
2587
+
2588
+ if number_format is not None:
2589
+ self.apply_style(cell, {"number_format": number_format})
2590
+
2591
+ class ConditionalFormatterBase:
2592
+
2593
+ def get_formatters(self, df):
2594
+ """Return a DataFrame the same dimensions as 'df' with the values
2595
+ set to a 'Formatter' where formatting should be applied and False
2596
+ or None otherwise.
2597
+ """
2598
+ raise NotImplementedError()
2599
+
2600
+ class ConditionalFormatter(ConditionalFormatterBase):
2601
+
2602
+ def __init__(self, expr, formatter, columns=None, **kwargs):
2603
+ """
2604
+ A ConditionalFormatter for use with DataFrameFormatter.
2605
+
2606
+ :param expr: Boolean expression for selecting rows to which the formatter will apply.
2607
+ :param formatter: Formatter that will be applied to the selected cells.
2608
+ :param columns: Column name or list of columns that the formatter will be applied to.
2609
+ May also be a callable, in which case it should accept a DataFrame and
2610
+ return a column or list of columns.
2611
+ :param kwargs: Additional arguments passed to DataFrame.eval when selecting the rows
2612
+ to apply the formatter to.
2613
+ """
2614
+ if "inplace" in kwargs:
2615
+ raise TypeError("inplace is an invalid keyword argument for ConditionalFormatter.")
2616
+ self.__expr = expr
2617
+ self.__columns = columns
2618
+ self.__kwargs = kwargs
2619
+
2620
+ if isinstance(formatter, dict):
2621
+ formatter = Formatter(**formatter)
2622
+ self.__formatter = formatter
2623
+
2624
+ def get_formatters(self, df):
2625
+ """See ConditionalFormatterBase.get_formatters"""
2626
+ # Create an empty DataFrame the same size as the source
2627
+ pd, np = _pandas_get_imports()
2628
+ formatters_df = pd.DataFrame(False, index=df.index, columns=df.columns, dtype=object)
2629
+
2630
+ # Query which rows should be included
2631
+ row_mask = df.eval(self.__expr, **self.__kwargs)
2632
+ if not row_mask.any():
2633
+ return None
2634
+
2635
+ col_mask = None
2636
+ if self.__columns:
2637
+ def _update_col_mask(col, col_mask):
2638
+ if callable(col):
2639
+ col = col(df)
2640
+ _update_col_mask(col, col_mask)
2641
+ elif isinstance(col, (list, tuple)):
2642
+ for c in col:
2643
+ _update_col_mask(c, col_mask)
2644
+ else:
2645
+ if col not in col_mask.index:
2646
+ raise RuntimeError("Invalid column '%s' found when applying conditional formatting." % str(col))
2647
+ col_mask[col] = True
2648
+
2649
+ col_mask = pd.Series(False, index=df.columns)
2650
+ _update_col_mask(self.__columns, col_mask)
2651
+
2652
+ if col_mask is None:
2653
+ formatters_df.loc[row_mask] = self.__formatter
2654
+ return formatters_df
2655
+
2656
+ formatters_df.loc[row_mask, col_mask] = self.__formatter
2657
+ return formatters_df
2658
+
2659
+ class DataFrameFormatter(Formatter):
2660
+ """Formatter for DataFrames.
2661
+
2662
+ For each argument expecting a Formatter, a dict may also be provided.
2663
+
2664
+ When a list of formatters is used (e.g. for the row or index formatters)
2665
+ the formatters will cycle through the list and repeat. For example, to
2666
+ format a table with striped rows only two row formatters are needed.
2667
+
2668
+ :param rows: Formatter or list of formatters to be applied to the rows.
2669
+ :param header: Formatter to use for the header column names.
2670
+ :param index: Formatter or list of formatters to be applied to the index.
2671
+ :param columns: Dict of column name to formatter or list of formatters to
2672
+ be applied for specific columns (in addition to the any
2673
+ row formatters).
2674
+ :param conditional_formatters: A list of ConditionalFormatters to be applied
2675
+ in order after any other formatting has
2676
+ been applied.
2677
+ :param kwargs: Additional Formatter kwargs that will affect the entire
2678
+ formatted range.
2679
+ """
2680
+
2681
+ default_header_formatter = Formatter(interior_color=0x8ED0A9)
2682
+
2683
+ default_index_formatter = Formatter(interior_color=0x8ED0A9)
2684
+
2685
+ default_row_formatters = [
2686
+ Formatter(interior_color=0xDBF1E4),
2687
+ Formatter(interior_color=0xF1F9F4),
2688
+ ]
2689
+
2690
+ def __init__(self,
2691
+ rows=default_row_formatters,
2692
+ header=default_header_formatter,
2693
+ index=default_index_formatter,
2694
+ columns=None,
2695
+ conditional_formatters=None,
2696
+ **kwargs):
2697
+ Formatter.__init__(self, **kwargs)
2698
+
2699
+ # row is a list of formatters to be used for each row in the DataFrame
2700
+ self.__row_formatters = None
2701
+ if rows:
2702
+ if not isinstance(rows, (list, tuple)):
2703
+ rows = [rows]
2704
+ self.__row_formatters = []
2705
+ for formatter in rows:
2706
+ formatter = self.__to_formatter(formatter)
2707
+ self.__row_formatters.append(formatter)
2708
+
2709
+ self.__header_formatter = None
2710
+ if header:
2711
+ self.__header_formatter = self.__to_formatter(header)
2712
+
2713
+ # index is a list of formatters to be used for each row in the index
2714
+ self.__index_formatters = None
2715
+ if index:
2716
+ if not isinstance(index, (list, tuple)):
2717
+ index = [index]
2718
+ self.__index_formatters = []
2719
+ for formatter in index:
2720
+ formatter = self.__to_formatter(formatter)
2721
+ self.__index_formatters.append(formatter)
2722
+
2723
+ # columns is a dict of columns to formatters or list of formatters
2724
+ self.__column_formatters = None
2725
+ if columns:
2726
+ if not isinstance(columns, dict):
2727
+ raise TypeError("Expected 'columns' to be a dict of formatters")
2728
+
2729
+ self.__column_formatters = {}
2730
+ for key, formatters in columns.items():
2731
+ if not isinstance(formatters, list):
2732
+ formatters = [formatters]
2733
+ self.__column_formatters[key] = []
2734
+ for formatter in formatters:
2735
+ formatter = self.__to_formatter(formatter)
2736
+ self.__column_formatters[key].append(formatter)
2737
+
2738
+ # Conditional formatters is a list of formatters to be applied in order
2739
+ self.__conditional_formatters = []
2740
+ if conditional_formatters is not None and not isinstance(conditional_formatters, (list, tuple)):
2741
+ raise TypeError("Expected 'conditional_formatters' to be a list of ConditionalFormatters")
2742
+ if conditional_formatters:
2743
+ for formatter in conditional_formatters:
2744
+ if isinstance(formatter, tuple):
2745
+ formatter = ConditionalFormatter(*formatter)
2746
+ elif isinstance(formatter, dict):
2747
+ formatter = ConditionalFormatter(**formatter)
2748
+ if not isinstance(formatter, ConditionalFormatterBase):
2749
+ raise TypeError("Expected 'conditional_formatters' to be a list of ConditionalFormatters")
2750
+ self.__conditional_formatters.append(formatter)
2751
+
2752
+ @staticmethod
2753
+ def __to_formatter(formatter):
2754
+ """helper to convert dict to formatter"""
2755
+ if isinstance(formatter, dict):
2756
+ formatter = Formatter(**formatter)
2757
+ return formatter
2758
+
2759
+ def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
2760
+ Formatter.apply(self,
2761
+ cell,
2762
+ value=value,
2763
+ datatype=datatype,
2764
+ datatype_ndim=datatype_ndim,
2765
+ datatype_kwargs=datatype_kwargs,
2766
+ transpose=transpose)
2767
+ # Convert the outer datatype to a TypeDescriptor
2768
+ type_desc = TypeDescriptor.create(datatype, kwargs=datatype_kwargs)
2769
+ if datatype_ndim:
2770
+ type_desc = type_desc.clone(ndim=datatype_ndim)
2771
+
2772
+ # Find the inner DataFrame type descriptor if it's not the outer one
2773
+ df_type_desc = type_desc
2774
+ if (("pandas.dataframe" not in df_type_desc.return_base_type_names
2775
+ and "dataframe" not in df_type_desc.return_base_type_names)
2776
+ or df_type_desc.ndim != 0):
2777
+ # Check for any inner types
2778
+ inner_dtypes = self._get_inner_type_descriptors(df_type_desc)
2779
+ for inner_dtype in inner_dtypes:
2780
+ if "pandas.dataframe" in inner_dtype.return_base_type_names \
2781
+ or "dataframe" in inner_dtype.return_base_type_names:
2782
+ df_type_desc = inner_dtype
2783
+ break
2784
+ else:
2785
+ _log.warning("DataFrameFormatter applied to a function without return type pandas.DataFrame: %s" % str(type_desc))
2786
+ return
2787
+
2788
+ pd, np = _pandas_get_imports()
2789
+ if not isinstance(value, pd.DataFrame):
2790
+ # If the type is not union or optional, and we were not passed a DataFrame, log a warning
2791
+ if df_type_desc is type_desc:
2792
+ _log.warning("DataFrameFormatter applied to a non-pandas.DataFrame result: %s" % type(value))
2793
+ return
2794
+
2795
+ df = value
2796
+ df_to_array = get_type_converter(df_type_desc, "__internal__")
2797
+ df_array = df_to_array(value)
2798
+
2799
+ header_rows = 0
2800
+ if df_type_desc.kwargs.get("columns", True):
2801
+ header_rows = 1
2802
+ if isinstance(df.columns, pd.MultiIndex):
2803
+ header_rows = len(df.columns.levels)
2804
+
2805
+ index_cols = 0
2806
+ if df_type_desc.kwargs.get("index", False):
2807
+ index_cols = 1
2808
+ if isinstance(df.index, pd.MultiIndex):
2809
+ index_cols = len(df.index.levels)
2810
+
2811
+ num_rows = len(df.index)
2812
+ num_cols = len(df.columns)
2813
+
2814
+ # Make sure the area we format is within the original range
2815
+ if transpose:
2816
+ max_rows = cell.columns
2817
+ max_cols = cell.rows
2818
+ else:
2819
+ max_rows = cell.rows
2820
+ max_cols = cell.columns
2821
+
2822
+ if (num_rows + header_rows) > max_rows:
2823
+ diff = (num_rows + header_rows) - max_rows
2824
+ deleted_rows = min(num_rows, diff)
2825
+ num_rows -= deleted_rows
2826
+ diff -= deleted_rows
2827
+ header_rows -= min(header_rows, diff)
2828
+
2829
+ if (num_cols + index_cols) > max_cols:
2830
+ diff = (num_cols + index_cols) - max_cols
2831
+ deleted_cols = min(diff, num_cols)
2832
+ num_cols -= deleted_cols
2833
+ diff -= deleted_cols
2834
+ index_cols -= min(index_cols, diff)
2835
+
2836
+ # Helper for transposing a range relative to the root range
2837
+ def _transpose(range, transpose):
2838
+ if not transpose:
2839
+ return range
2840
+ r = range.rect.first_row - cell.rect.first_row
2841
+ c = range.rect.first_col - cell.rect.first_col
2842
+ return cell.offset(c, r).resize(range.columns, range.rows)
2843
+
2844
+ if self.__header_formatter and header_rows and (num_cols or index_cols):
2845
+ header_range = cell.resize(header_rows, num_cols + index_cols)
2846
+ self.__header_formatter.apply(_transpose(header_range, transpose),
2847
+ df_array[:header_rows],
2848
+ datatype="var",
2849
+ datatype_ndim=2,
2850
+ transpose=transpose)
2851
+
2852
+ if self.__row_formatters and num_rows and (num_cols or index_cols):
2853
+ if len(self.__row_formatters) == 1:
2854
+ rows_range = cell.offset(header_rows, 0).resize(num_rows, num_cols + index_cols)
2855
+ formatter = self.__row_formatters[0]
2856
+ formatter.apply(_transpose(rows_range, transpose),
2857
+ df_array[header_rows:num_rows+header_rows],
2858
+ datatype="var",
2859
+ datatype_ndim=2,
2860
+ transpose=transpose)
2861
+ else:
2862
+ for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
2863
+ row_range = cell.offset(i + header_rows, 0).resize(1, num_cols + index_cols)
2864
+ formatter = self.__row_formatters[i % len(self.__row_formatters)]
2865
+ formatter.apply(_transpose(row_range, transpose),
2866
+ df_array[i+header_rows],
2867
+ datatype="var",
2868
+ datatype_ndim=1,
2869
+ transpose=transpose)
2870
+
2871
+ if self.__index_formatters and index_cols and num_rows:
2872
+ if len(self.__index_formatters) == 1:
2873
+ index_range = cell.offset(header_rows, 0).resize(num_rows, index_cols)
2874
+ formatter = self.__index_formatters[0]
2875
+ formatter.apply(_transpose(index_range, transpose),
2876
+ [x[:index_cols] for x in df_array[header_rows:num_rows+header_rows]],
2877
+ datatype="var",
2878
+ datatype_ndim=2,
2879
+ transpose=transpose)
2880
+ else:
2881
+ for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
2882
+ index_range = cell.offset(i + header_rows, 0).resize(1, index_cols)
2883
+ formatter = self.__index_formatters[i % len(self.__index_formatters)]
2884
+ formatter.apply(_transpose(index_range, transpose),
2885
+ df_array[i+header_rows][:index_cols],
2886
+ datatype="var",
2887
+ datatype_ndim=1,
2888
+ transpose=transpose)
2889
+
2890
+ if self.__column_formatters and num_rows:
2891
+ for col, formatters in self.__column_formatters.items():
2892
+ try:
2893
+ col_idx = df.columns.get_loc(col)
2894
+ except KeyError:
2895
+ continue
2896
+
2897
+ if col_idx >= num_cols:
2898
+ continue
2899
+
2900
+ if len(formatters) == 1:
2901
+ col_range = cell.offset(header_rows, col_idx + index_cols).resize(num_rows, 1)
2902
+ formatter = formatters[0]
2903
+ formatter.apply(_transpose(col_range, transpose),
2904
+ [[x[col_idx+index_cols]] for x in df_array[header_rows:num_rows+header_rows]],
2905
+ datatype="var",
2906
+ datatype_ndim=2,
2907
+ transpose=transpose)
2908
+ else:
2909
+ for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
2910
+ cel_range = cell.offset(i + header_rows, col_idx + index_cols)
2911
+ formatter = formatters[i % len(formatters)]
2912
+ formatter.apply(_transpose(cel_range, transpose),
2913
+ df_array[header_rows+i][col_idx+index_cols],
2914
+ datatype="var",
2915
+ datatype_ndim=0,
2916
+ transpose=transpose)
2917
+
2918
+ # Apply the conditional formatters if there are any
2919
+ if self.__conditional_formatters and num_rows:
2920
+ to_array = get_type_converter("pandas.dataframe", "__internal__", src_kwargs={"index": False, "columns": False})
2921
+ for conditional_formatter in self.__conditional_formatters:
2922
+ formatter_df = conditional_formatter.get_formatters(df)
2923
+ if formatter_df is None:
2924
+ continue
2925
+
2926
+ if df.shape != formatter_df.shape:
2927
+ raise RuntimeError("A ConditionalFormatter returned a DataFrame of the wrong shape.")
2928
+
2929
+ formatter_array = to_array(formatter_df)
2930
+ for r, row in enumerate(formatter_array[:num_rows]):
2931
+ for c, formatter in enumerate(row[:num_cols]):
2932
+ if not formatter or pd.isnull(formatter):
2933
+ continue
2934
+
2935
+ formatter = self.__to_formatter(formatter)
2936
+ cell_to_format = cell.offset(header_rows + r, index_cols + c)
2937
+ formatter.apply(_transpose(cell_to_format, transpose),
2938
+ df_array[header_rows + r][index_cols + c],
2939
+ datatype="var",
2940
+ datatype_ndim=0,
2941
+ transpose=transpose)
2942
+
2943
+ # Custom task panes and ActiveX controls
2944
+
2945
+ class UIBridge:
2946
+ """Base class of bridges between the Python UI toolkits
2947
+ and PyXLL's Custom Task Panes.
2948
+ """
2949
+
2950
+ def __init__(self, control):
2951
+ self.__timer_interval = 0.1
2952
+ self.__has_focus = False
2953
+ self.control = control
2954
+
2955
+ def close(self):
2956
+ pass
2957
+
2958
+ def get_hwnd(self):
2959
+ raise NotImplementedError()
2960
+
2961
+ def pre_attach(self, hwnd):
2962
+ pass
2963
+
2964
+ def post_attach(self, hwnd):
2965
+ pass
2966
+
2967
+ def on_close(self):
2968
+ pass
2969
+
2970
+ def on_window_closed(self):
2971
+ pass
2972
+
2973
+ def on_window_destroyed(self):
2974
+ pass
2975
+
2976
+ def process_message(self, hwnd, msg, wparam, lparam):
2977
+ pass
2978
+
2979
+ def translate_accelerator(self, hwnd, msg, wparam, lparam, modifier):
2980
+ pass
2981
+
2982
+ def filter_message(self, hwnd, msg, wparam, lparam):
2983
+ pass
2984
+
2985
+ def __set_has_focus(self, has_focus):
2986
+ self.__has_focus = has_focus
2987
+
2988
+ def __get_has_focus(self):
2989
+ return self.__has_focus
2990
+
2991
+ has_focus = property(__get_has_focus, __set_has_focus)
2992
+
2993
+ def __set_timer_interval(self, interval):
2994
+ self.__timer_interval = interval
2995
+
2996
+ def __get_timer_interval(self):
2997
+ return self.__timer_interval
2998
+
2999
+ timer_interval = property(__get_timer_interval, __set_timer_interval)
3000
+
3001
+ def on_timer(self):
3002
+ pass
3003
+
3004
+ CTPDockPositionLeft = 0
3005
+ CTPDockPositionTop = 1
3006
+ CTPDockPositionRight = 2
3007
+ CTPDockPositionBottom = 3
3008
+ CTPDockPositionFloating = 4
3009
+
3010
+ CTPDockPositionRestrictNone = 0
3011
+ CTPDockPositionRestrictNoChange = 1
3012
+ CTPDockPositionRestrictNoHorizontal = 2
3013
+ CTPDockPositionRestrictNoVertical = 3
3014
+
3015
+ class CTPBridgeBase(UIBridge):
3016
+ """Base class of bridges between the Python UI toolkits
3017
+ and PyXLL's Custom Task Panes.
3018
+ """
3019
+
3020
+ def get_title(self):
3021
+ pass
3022
+
3023
+ def xl_ctp_bridge(*clsnames):
3024
+ """Decorator to apply to implementations of the CTPBridgeBase class
3025
+ to register that class as the default bridge for a UI control.
3026
+
3027
+ For example::
3028
+
3029
+ @xl_ctp_bridge("myuilib.Widget")
3030
+ class MyUIBridge(CTPBridgeBase):
3031
+ ...
3032
+
3033
+ After registering a bridge class, any call to `pyxll.create_ctp`
3034
+ with an object of the types specified will use the registered bridge.
3035
+ """
3036
+ def xl_ctp_bridge_decorator(bridge_cls):
3037
+ return bridge_cls
3038
+ return xl_ctp_bridge_decorator
3039
+
3040
+ class CustomTaskPane:
3041
+
3042
+ def __init__(self, *args, **kwargs):
3043
+ raise Exception("Not supported when running outside of Excel")
3044
+
3045
+ def Delete(self):
3046
+ raise Exception("Not supported when running outside of Excel")
3047
+
3048
+ Title = None
3049
+ Application = None
3050
+ Window = None
3051
+ Visible = False
3052
+ ContentControl = None
3053
+ Width = 0
3054
+ Height = 0
3055
+ DockPosition = CTPDockPositionRight
3056
+ DockPositionRestrict = CTPDockPositionRestrictNone
3057
+
3058
+ def create_ctp(control,
3059
+ title=None,
3060
+ width=None,
3061
+ height=None,
3062
+ position=CTPDockPositionRight,
3063
+ position_restrict=CTPDockPositionRestrictNone,
3064
+ top=None,
3065
+ left=None,
3066
+ timer_interval=0.1,
3067
+ bridge_cls=None): # type: (...) -> CustomTaskPane
3068
+ """Creates a Custom Task Pane from a UI control object.
3069
+
3070
+ The control object can be any of the following:
3071
+ - tkinter.Toplevel
3072
+ - PyQt5.QtWidgets.QWidget
3073
+ - PySide2.QtWidgets.QWidget
3074
+ - wx.Frame
3075
+
3076
+ :param control: UI control of one of the supported types.
3077
+ :param title: Title of the custom task pane to be created.
3078
+ :param width: Initial width of the custom task pane.
3079
+ :param height: Initial height of the custom task pane.
3080
+ :param position: Where to display the custom task pane. Can be any of:
3081
+ - CTPDockPositionLeft
3082
+ - CTPDockPositionTop
3083
+ - CTPDockPositionRight
3084
+ - CTPDockPositionBottom
3085
+ - CTPDockPositionFloating
3086
+ :param position_restrict: Restriction on where the custom task pane can be positions. Can be any of:
3087
+ - CTPDockPositionRestrictNone
3088
+ - CTPDockPositionRestrictNoChange
3089
+ - CTPDockPositionRestrictNoHorizontal
3090
+ - CTPDockPositionRestrictNoVertical
3091
+ :param top: Initial top position of custom task pane (only used if floating).
3092
+ :param left: Initial left position of custom task pane (only used if floating).
3093
+ :param timer_interval: The interval in seconds between calls to :py:meth:`CTPBridgeBase.on_timer`.
3094
+ :param bridge_cls: Subclass of :py:class:`CTPBridgeBase` to use. For supported widget types this
3095
+ is chosen automatically.
3096
+ """
3097
+ raise Exception("Not supported when running outside of Excel")
3098
+
3099
+ class AtxBridgeBase(UIBridge):
3100
+ """Base class of bridges between the Python UI toolkits
3101
+ and PyXLL's ActiveX control.
3102
+ """
3103
+
3104
+ def width(self, dpi):
3105
+ """Return the width of the control, in points."""
3106
+ return NotImplementedError()
3107
+
3108
+ def height(self, dpi):
3109
+ """Return the height of the control, in points."""
3110
+ return NotImplementedError()
3111
+
3112
+ def xl_activex_bridge(*clsnames):
3113
+ """Decorator to apply to implementations of the AtxBridgeBase class
3114
+ to register that class as the default bridge for a UI control.
3115
+
3116
+ For example::
3117
+
3118
+ @xl_activex_bridge("myuilib.Widget")
3119
+ class MyUIBridge(AtxBridgeBase):
3120
+ ...
3121
+
3122
+ After registering a bridge class, any call to `pyxll.create_activex_control`
3123
+ with an object of the types specified will use the registered bridge.
3124
+ """
3125
+ def xl_activex_bridge_decorator(bridge_cls):
3126
+ return bridge_cls
3127
+ return xl_activex_bridge_decorator
3128
+
3129
+ class ActiveXHost:
3130
+ """ActiveX object returned by create_activex_control."""
3131
+
3132
+ def __init__(self):
3133
+ raise Exception("Not supported when running outside of Excel")
3134
+
3135
+ def Invalidate(self):
3136
+ """Requests Excel redraws the control."""
3137
+ raise Exception("Not supported when running outside of Excel")
3138
+
3139
+ def create_activex_control(control,
3140
+ name=None,
3141
+ sheet=None,
3142
+ width=None,
3143
+ height=None,
3144
+ top=None,
3145
+ left=None,
3146
+ timer_interval=0.1,
3147
+ bridge_cls=None): # type: (...) -> ActiveXHost
3148
+ """Creates an ActiveX control from a UI control object.
3149
+
3150
+ The control object can be any of the following:
3151
+ - tkinter.Toplevel
3152
+ - PyQt5.QtWidgets.QWidget
3153
+ - PySide2.QtWidgets.QWidget
3154
+ - wx.Frame
3155
+ """
3156
+ raise Exception("Not supported when running outside of Excel")
3157
+
3158
+ # Plotting
3159
+
3160
+ class PlotBridgeBase:
3161
+
3162
+ def __init__(self, figure):
3163
+ self.figure = figure
3164
+
3165
+ def clone(self):
3166
+ raise NotImplementedError()
3167
+
3168
+ def can_export(self, format):
3169
+ """Return True if the figure can be exported in a specific format.
3170
+ Formats are svg and png.
3171
+ """
3172
+ return False
3173
+
3174
+ def get_size_hint(self, dpi):
3175
+ """Return (width, height) tuple the figure should be exported as
3176
+ or None. Width and height are in points (72th of an inch)."""
3177
+ return None
3178
+
3179
+ def export(self, width, height, dpi, format, filename, **kwargs):
3180
+ """Export the figure to a file as a given size and format.
3181
+
3182
+ Can return a callable that will be called when any resources
3183
+ generated on export are no longer required.
3184
+ """
3185
+ raise NotImplementedError()
3186
+
3187
+ def xl_plot_bridge(*clsnames):
3188
+ """Decorator to apply to implementations of the PlotBridgeBase class
3189
+ to register that class as the default bridge for a plot type.
3190
+
3191
+ For example::
3192
+
3193
+ @xl_plot_bridge("myplotlib.Chart")
3194
+ class MyPlotLibBridge(PlotBridgeBase):
3195
+ ...
3196
+
3197
+ After registering a plotting bridge class, any call to `pyxll.plot` with
3198
+ an object of the types specified will use the registered bridge.
3199
+ """
3200
+ def xl_plot_bridge_decorator(bridge_cls):
3201
+ return bridge_cls
3202
+ return xl_plot_bridge_decorator
3203
+
3204
+ def plot(figure=None,
3205
+ name=None,
3206
+ width=None,
3207
+ height=None,
3208
+ top=None,
3209
+ left=None,
3210
+ sheet=None,
3211
+ allow_html=None,
3212
+ allow_svg=None,
3213
+ allow_resize=None,
3214
+ alt_text=None,
3215
+ reset=False,
3216
+ bridge_cls=None,
3217
+ **kwargs):
3218
+ """Plots a figure to Excel as an embedded image.
3219
+
3220
+ The figure can be any of the following:
3221
+
3222
+ - A matplotlib Figure object
3223
+
3224
+ :param figure: Figure to plot. This can be an instance of any of the following:
3225
+
3226
+ - matplotlib.figure.Figure
3227
+ - plotly.graph_objects.Figure
3228
+ - bokeh.models.plots.Plot
3229
+
3230
+ If none, the active matplotlib.pyplot figure is used.
3231
+
3232
+ :param name: Name of Picture object in Excel. If this is None then
3233
+ a name will be chosen, and if called from a UDF then
3234
+ repeated calls with re-use the same name.
3235
+
3236
+ :param width: Width of the picture in Excel, in points.
3237
+ If set then height must also be set.
3238
+ If None the width will be taken from the figure.
3239
+
3240
+ :param height: Height of the picture in Excel, in points.
3241
+ If set then width must also be set.
3242
+ If None the height will be taken from the figure.
3243
+
3244
+ :param top: Location of the top of the plot in Excel, in points.
3245
+ If set then left must also be set.
3246
+ If None, the picture will be placed below the current or selected cell.
3247
+
3248
+ :param left: Location of the left of the plot in Excel, in points.
3249
+ If set then top must also be set.
3250
+ If None, the picture will be placed below the current or selected cell.
3251
+
3252
+ :param sheet: Name of the sheet to add the picture to. If none, the current sheet is used.
3253
+
3254
+ :param allow_html: Some figures may be rendered as HTML, if WebView2 is installed.
3255
+ This can be disabled by setting this option to False, or by using the
3256
+ config setting ``plot_allow_html = 0``.
3257
+
3258
+ :param allow_svg: Some figures may be rendered as SVG, if the version of Excel allows.
3259
+ This can be disabled by setting this option to False, or by using the
3260
+ config setting ``plot_allow_svg = 0``.
3261
+
3262
+ :param allow_resize: When allowed (default), figures will be redrawn when the shape in Excel is resized.
3263
+ This can be disabled by setting this option to False, or by using the
3264
+ config setting ``plot_allow_resize = 0``.
3265
+
3266
+ :param alt_text: Alternative (descriptive) text to use for the picture object in Excel. This can
3267
+ be displayed instead of the shape object if the Excel document is saved to a web page,
3268
+ or when the mouse hovers over the image (if supported by the browser).
3269
+
3270
+ :param reset: Reset the size and position of the image.
3271
+
3272
+ :param kwargs: Additional arguments will be called to the implementation specific
3273
+ method for exporting the figure to an image.
3274
+ """
3275
+ raise Exception("Not supported when running outside of Excel")
3276
+
3277
+ # Context managers
3278
+
3279
+ class _DisableUpdatesContextManager:
3280
+
3281
+ def __init__(self, flags):
3282
+ self.__flags = flags
3283
+
3284
+ def __enter__(self):
3285
+ pass
3286
+
3287
+ def __exit__(self, exc_type, exc_val, exc_tb):
3288
+ pass
3289
+
3290
+ def xl_disable(automatic_calculations=True,
3291
+ screen_updating=True,
3292
+ alerts=True,
3293
+ restore_selection=True,
3294
+ restore_active_sheet=True):
3295
+ """
3296
+ Context manager to disable Excel while performing operations
3297
+ that interact with Excel.
3298
+
3299
+ Can only be used from inside an Excel macro, or from a function
3300
+ scheduled using pyxll.schedule_call.
3301
+
3302
+ Example::
3303
+
3304
+ @xl_macro
3305
+ def macro_function():
3306
+ with xl_disable():
3307
+ # do some work here that updates Excel where we do not
3308
+ # want Excel to automatically recalculate or update.
3309
+ xl = xl_app()
3310
+ xl.Range("A1").Value = 1
3311
+
3312
+ # After the with block, Excel reverts to its previous calculation mode.
3313
+ return
3314
+
3315
+ :param automatic_calculations: Disable automatic calculations until finished.
3316
+ :param screen_updating: Disable screen updating until finished.
3317
+ :param alerts: Disable alerts until finished.
3318
+ :param restore_selection: Restore the current selection when finished.
3319
+ :param restore_active_sheet: Restore the current active sheet when finished.
3320
+ """
3321
+ flags = 0
3322
+ return _DisableUpdatesContextManager(flags)
3323
+
3324
+ # Events
3325
+
3326
+ _EventHandler = typing.TypeVar("_EventHandler", bound=typing.Callable[..., typing.Any])
3327
+ _EventFilter = typing.TypeVar("_EventFilter", bound=typing.Callable[..., bool], contravariant=True)
3328
+
3329
+ class _EventHandlerDecorator(typing.Protocol[_EventHandler, _EventFilter]):
3330
+ @typing.overload
3331
+ def __call__(self,
3332
+ func: _EventHandler,
3333
+ filter: typing.Optional[_EventFilter] = None,
3334
+ com_package: typing.Optional[str] = None) -> _EventHandler: ...
3335
+
3336
+ @typing.overload
3337
+ def __call__(self,
3338
+ func: None = None,
3339
+ filter: typing.Optional[_EventFilter] = None,
3340
+ com_package: typing.Optional[str] = None) -> typing.Callable[[_EventHandler], _EventHandler]: ...
3341
+
3342
+ class _NewWorkbookFunc(typing.Protocol):
3343
+ def __call__(self, workbook): ...
3344
+
3345
+ class _NewWorkbookFilter(typing.Protocol):
3346
+ def __call__(self, workbook) -> bool: ...
3347
+
3348
+ _NewWorkbookDecorator = _EventHandlerDecorator[_NewWorkbookFunc, _NewWorkbookFilter]
3349
+
3350
+ class _SheetSelectionChangeFunc(typing.Protocol):
3351
+ def __call__(self, sheet, target): ...
3352
+
3353
+ class _SheetSelectionChangeFilter(typing.Protocol):
3354
+ def __call__(self, sheet, target) -> bool: ...
3355
+
3356
+ _SheetSelectionChangeDecorator = _EventHandlerDecorator[_SheetSelectionChangeFunc, _SheetSelectionChangeFilter]
3357
+
3358
+ class _SheetBeforeDoubleClickFunc(typing.Protocol):
3359
+ def __call__(self, sheet, target, cancel) -> typing.Optional[bool]: ...
3360
+
3361
+ class _SheetBeforeDoubleClickFilter(typing.Protocol):
3362
+ def __call__(self, sheet, target, cancel) -> bool: ...
3363
+
3364
+ _SheetBeforeDoubleClickDecorator = _EventHandlerDecorator[_SheetBeforeDoubleClickFunc, _SheetBeforeDoubleClickFilter]
3365
+
3366
+ class _SheetBeforeRightClickFunc(typing.Protocol):
3367
+ def __call__(self, sheet, target, cancel) -> typing.Optional[bool]: ...
3368
+
3369
+ class _SheetBeforeRightClickFilter(typing.Protocol):
3370
+ def __call__(self, sheet, target, cancel) -> bool: ...
3371
+
3372
+ _SheetBeforeRightClickDecorator = _EventHandlerDecorator[_SheetBeforeRightClickFunc, _SheetBeforeRightClickFilter]
3373
+
3374
+ class _SheetActivateFunc(typing.Protocol):
3375
+ def __call__(self, sheet): ...
3376
+
3377
+ class _SheetActivateFilter(typing.Protocol):
3378
+ def __call__(self, sheet) -> bool: ...
3379
+
3380
+ _SheetActivateDecorator = _EventHandlerDecorator[_SheetActivateFunc, _SheetActivateFilter]
3381
+
3382
+ class _SheetDeactivateFunc(typing.Protocol):
3383
+ def __call__(self, sheet): ...
3384
+
3385
+ class _SheetDeactivateFilter(typing.Protocol):
3386
+ def __call__(self, sheet) -> bool: ...
3387
+
3388
+ _SheetDeactivateDecorator = _EventHandlerDecorator[_SheetDeactivateFunc, _SheetDeactivateFilter]
3389
+
3390
+ class _SheetCalculateFunc(typing.Protocol):
3391
+ def __call__(self, sheet): ...
3392
+
3393
+ class _SheetCalculateFilter(typing.Protocol):
3394
+ def __call__(self, sheet) -> bool: ...
3395
+
3396
+ _SheetCalculateDecorator = _EventHandlerDecorator[_SheetCalculateFunc, _SheetCalculateFilter]
3397
+
3398
+ class _SheetChangeFunc(typing.Protocol):
3399
+ def __call__(self, sheet, target): ...
3400
+
3401
+ class _SheetChangeFilter(typing.Protocol):
3402
+ def __call__(self, sheet, target) -> bool: ...
3403
+
3404
+ _SheetChangeDecorator = _EventHandlerDecorator[_SheetChangeFunc, _SheetChangeFilter]
3405
+
3406
+ class _WorkbookOpenFunc(typing.Protocol):
3407
+ def __call__(self, workbook): ...
3408
+
3409
+ class _WorkbookOpenFilter(typing.Protocol):
3410
+ def __call__(self, workbook) -> bool: ...
3411
+
3412
+ _WorkbookOpenDecorator = _EventHandlerDecorator[_WorkbookOpenFunc, _WorkbookOpenFilter]
3413
+
3414
+ class _WorkbookActivateFunc(typing.Protocol):
3415
+ def __call__(self, workbook): ...
3416
+
3417
+ class _WorkbookActivateFilter(typing.Protocol):
3418
+ def __call__(self, workbook) -> bool: ...
3419
+
3420
+ _WorkbookActivateDecorator = _EventHandlerDecorator[_WorkbookActivateFunc, _WorkbookActivateFilter]
3421
+
3422
+ class _WorkbookDeactivateFunc(typing.Protocol):
3423
+ def __call__(self, workbook): ...
3424
+
3425
+ class _WorkbookDeactivateFilter(typing.Protocol):
3426
+ def __call__(self, workbook) -> bool: ...
3427
+
3428
+ _WorkbookDeactivateDecorator = _EventHandlerDecorator[_WorkbookDeactivateFunc, _WorkbookDeactivateFilter]
3429
+
3430
+ class _WorkbookBeforeCloseFunc(typing.Protocol):
3431
+ def __call__(self, workbook, cancel) -> typing.Optional[bool]: ...
3432
+
3433
+ class _WorkbookBeforeCloseFilter(typing.Protocol):
3434
+ def __call__(self, workbook, cancel) -> bool: ...
3435
+
3436
+ _WorkbookBeforeCloseDecorator = _EventHandlerDecorator[_WorkbookBeforeCloseFunc, _WorkbookBeforeCloseFilter]
3437
+
3438
+ class _WorkbookBeforeSaveFunc(typing.Protocol):
3439
+ def __call__(self, workbook, save_as_ui, cancel) -> typing.Optional[bool]: ...
3440
+
3441
+ class _WorkbookBeforeSaveFilter(typing.Protocol):
3442
+ def __call__(self, workbook, save_as_ui, cancel) -> bool: ...
3443
+
3444
+ _WorkbookBeforeSaveDecorator = _EventHandlerDecorator[_WorkbookBeforeSaveFunc, _WorkbookBeforeSaveFilter]
3445
+
3446
+ class _WorkbookBeforePrintFunc(typing.Protocol):
3447
+ def __call__(self, workbook, cancel) -> typing.Optional[bool]: ...
3448
+
3449
+ class _WorkbookBeforePrintFilter(typing.Protocol):
3450
+ def __call__(self, workbook, cancel) -> bool: ...
3451
+
3452
+ _WorkbookBeforePrintDecorator = _EventHandlerDecorator[_WorkbookBeforePrintFunc, _WorkbookBeforePrintFilter]
3453
+
3454
+ class _WorkbookNewSheetFunc(typing.Protocol):
3455
+ def __call__(self, workbook, sheet): ...
3456
+
3457
+ class _WorkbookNewSheetFilter(typing.Protocol):
3458
+ def __call__(self, workbook, sheet) -> bool: ...
3459
+
3460
+ _WorkbookNewSheetDecorator = _EventHandlerDecorator[_WorkbookNewSheetFunc, _WorkbookNewSheetFilter]
3461
+
3462
+ class _WorkbookAddinInstallFunc(typing.Protocol):
3463
+ def __call__(self, workbook): ...
3464
+
3465
+ class _WorkbookAddinInstallFilter(typing.Protocol):
3466
+ def __call__(self, workbook) -> bool: ...
3467
+
3468
+ _WorkbookAddinInstallDecorator = _EventHandlerDecorator[_WorkbookAddinInstallFunc, _WorkbookAddinInstallFilter]
3469
+
3470
+ class _WorkbookAddinUninstallFunc(typing.Protocol):
3471
+ def __call__(self, workbook): ...
3472
+
3473
+ class _WorkbookAddinUninstallFilter(typing.Protocol):
3474
+ def __call__(self, workbook) -> bool: ...
3475
+
3476
+ _WorkbookAddinUninstallDecorator = _EventHandlerDecorator[_WorkbookAddinUninstallFunc, _WorkbookAddinUninstallFilter]
3477
+
3478
+ class _WindowResizeFunc(typing.Protocol):
3479
+ def __call__(self, workbook, wn): ...
3480
+
3481
+ class _WindowResizeFilter(typing.Protocol):
3482
+ def __call__(self, workbook, wn) -> bool: ...
3483
+
3484
+ _WindowResizeDecorator = _EventHandlerDecorator[_WindowResizeFunc, _WindowResizeFilter]
3485
+
3486
+ class _WindowActivateFunc(typing.Protocol):
3487
+ def __call__(self, workbook, wn): ...
3488
+
3489
+ class _WindowActivateFilter(typing.Protocol):
3490
+ def __call__(self, workbook, wn) -> bool: ...
3491
+
3492
+ _WindowActivateDecorator = _EventHandlerDecorator[_WindowActivateFunc, _WindowActivateFilter]
3493
+
3494
+ class _WindowDeactivateFunc(typing.Protocol):
3495
+ def __call__(self, workbook, wn): ...
3496
+
3497
+ class _WindowDeactivateFilter(typing.Protocol):
3498
+ def __call__(self, workbook, wn) -> bool: ...
3499
+
3500
+ _WindowDeactivateDecorator = _EventHandlerDecorator[_WindowDeactivateFunc, _WindowDeactivateFilter]
3501
+
3502
+ class _SheetFollowHyperlinkFunc(typing.Protocol):
3503
+ def __call__(self, sheet, target): ...
3504
+
3505
+ class _SheetFollowHyperlinkFilter(typing.Protocol):
3506
+ def __call__(self, sheet, target) -> bool: ...
3507
+
3508
+ _SheetFollowHyperlinkDecorator = _EventHandlerDecorator[_SheetFollowHyperlinkFunc, _SheetFollowHyperlinkFilter]
3509
+
3510
+ class _SheetPivotTableUpdateFunc(typing.Protocol):
3511
+ def __call__(self, sheet, target): ...
3512
+
3513
+ class _SheetPivotTableUpdateFilter(typing.Protocol):
3514
+ def __call__(self, sheet, target) -> bool: ...
3515
+
3516
+ _SheetPivotTableUpdateDecorator = _EventHandlerDecorator[_SheetPivotTableUpdateFunc, _SheetPivotTableUpdateFilter]
3517
+
3518
+ class _WorkbookPivotTableCloseConnectionFunc(typing.Protocol):
3519
+ def __call__(self, workbook, target): ...
3520
+
3521
+ class _WorkbookPivotTableCloseConnectionFilter(typing.Protocol):
3522
+ def __call__(self, workbook, target) -> bool: ...
3523
+
3524
+ _WorkbookPivotTableCloseConnectionDecorator = _EventHandlerDecorator[_WorkbookPivotTableCloseConnectionFunc, _WorkbookPivotTableCloseConnectionFilter]
3525
+
3526
+ class _WorkbookPivotTableOpenConnectionFunc(typing.Protocol):
3527
+ def __call__(self, workbook, target): ...
3528
+
3529
+ class _WorkbookPivotTableOpenConnectionFilter(typing.Protocol):
3530
+ def __call__(self, workbook, target) -> bool: ...
3531
+
3532
+ _WorkbookPivotTableOpenConnectionDecorator = _EventHandlerDecorator[_WorkbookPivotTableOpenConnectionFunc, _WorkbookPivotTableOpenConnectionFilter]
3533
+
3534
+ class _WorkbookSyncFunc(typing.Protocol):
3535
+ def __call__(self, workbook, sync_event_type): ...
3536
+
3537
+ class _WorkbookSyncFilter(typing.Protocol):
3538
+ def __call__(self, workbook, sync_event_type) -> bool: ...
3539
+
3540
+ _WorkbookSyncDecorator = _EventHandlerDecorator[_WorkbookSyncFunc, _WorkbookSyncFilter]
3541
+
3542
+ class _WorkbookBeforeXmlImportFunc(typing.Protocol):
3543
+ def __call__(self, workbook, xml_map, url, is_refresh, cancel) -> typing.Optional[bool]: ...
3544
+
3545
+ class _WorkbookBeforeXmlImportFilter(typing.Protocol):
3546
+ def __call__(self, workbook, xml_map, url, is_refresh, cancel) -> bool: ...
3547
+
3548
+ _WorkbookBeforeXmlImportDecorator = _EventHandlerDecorator[_WorkbookBeforeXmlImportFunc, _WorkbookBeforeXmlImportFilter]
3549
+
3550
+ class _WorkbookAfterXmlImportFunc(typing.Protocol):
3551
+ def __call__(self, workbook, xml_map, is_refresh, result): ...
3552
+
3553
+ class _WorkbookAfterXmlImportFilter(typing.Protocol):
3554
+ def __call__(self, workbook, xml_map, is_refresh, result) -> bool: ...
3555
+
3556
+ _WorkbookAfterXmlImportDecorator = _EventHandlerDecorator[_WorkbookAfterXmlImportFunc, _WorkbookAfterXmlImportFilter]
3557
+
3558
+ class _WorkbookBeforeXmlExportFunc(typing.Protocol):
3559
+ def __call__(self, workbook, xml_map, url, cancel) -> typing.Optional[bool]: ...
3560
+
3561
+ class _WorkbookBeforeXmlExportFilter(typing.Protocol):
3562
+ def __call__(self, workbook, xml_map, url, cancel) -> bool: ...
3563
+
3564
+ _WorkbookBeforeXmlExportDecorator = _EventHandlerDecorator[_WorkbookBeforeXmlExportFunc, _WorkbookBeforeXmlExportFilter]
3565
+
3566
+ class _WorkbookAfterXmlExportFunc(typing.Protocol):
3567
+ def __call__(self, workbook, xml_map, url, result): ...
3568
+
3569
+ class _WorkbookAfterXmlExportFilter(typing.Protocol):
3570
+ def __call__(self, workbook, xml_map, url, result) -> bool: ...
3571
+
3572
+ _WorkbookAfterXmlExportDecorator = _EventHandlerDecorator[_WorkbookAfterXmlExportFunc, _WorkbookAfterXmlExportFilter]
3573
+
3574
+ class _WorkbookRowsetCompleteFunc(typing.Protocol):
3575
+ def __call__(self, workbook, description, sheet, success): ...
3576
+
3577
+ class _WorkbookRowsetCompleteFilter(typing.Protocol):
3578
+ def __call__(self, workbook, description, sheet, success) -> bool: ...
3579
+
3580
+ _WorkbookRowsetCompleteDecorator = _EventHandlerDecorator[_WorkbookRowsetCompleteFunc, _WorkbookRowsetCompleteFilter]
3581
+
3582
+ class _AfterCalculateFunc(typing.Protocol):
3583
+ def __call__(self): ...
3584
+
3585
+ class _AfterCalculateFilter(typing.Protocol):
3586
+ def __call__(self) -> bool: ...
3587
+
3588
+ _AfterCalculateDecorator = _EventHandlerDecorator[_AfterCalculateFunc, _AfterCalculateFilter]
3589
+
3590
+ class _SheetPivotTableAfterValueChangeFunc(typing.Protocol):
3591
+ def __call__(self, sheet, target_pivot_table, target_range): ...
3592
+
3593
+ class _SheetPivotTableAfterValueChangeFilter(typing.Protocol):
3594
+ def __call__(self, sheet, target_pivot_table, target_range) -> bool: ...
3595
+
3596
+ _SheetPivotTableAfterValueChangeDecorator = _EventHandlerDecorator[_SheetPivotTableAfterValueChangeFunc, _SheetPivotTableAfterValueChangeFilter]
3597
+
3598
+ class _SheetPivotTableBeforeAllocateChangesFunc(typing.Protocol):
3599
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end, cancel) -> typing.Optional[bool]: ...
3600
+
3601
+ class _SheetPivotTableBeforeAllocateChangesFilter(typing.Protocol):
3602
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end, cancel) -> bool: ...
3603
+
3604
+ _SheetPivotTableBeforeAllocateChangesDecorator = _EventHandlerDecorator[_SheetPivotTableBeforeAllocateChangesFunc, _SheetPivotTableBeforeAllocateChangesFilter]
3605
+
3606
+ class _SheetPivotTableBeforeCommitChangesFunc(typing.Protocol):
3607
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end, cancel) -> typing.Optional[bool]: ...
3608
+
3609
+ class _SheetPivotTableBeforeCommitChangesFilter(typing.Protocol):
3610
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end, cancel) -> bool: ...
3611
+
3612
+ _SheetPivotTableBeforeCommitChangesDecorator = _EventHandlerDecorator[_SheetPivotTableBeforeCommitChangesFunc, _SheetPivotTableBeforeCommitChangesFilter]
3613
+
3614
+ class _SheetPivotTableBeforeDiscardChangesFunc(typing.Protocol):
3615
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end): ...
3616
+
3617
+ class _SheetPivotTableBeforeDiscardChangesFilter(typing.Protocol):
3618
+ def __call__(self, sheet, target_pivot_table, value_change_start, value_change_end) -> bool: ...
3619
+
3620
+ _SheetPivotTableBeforeDiscardChangesDecorator = _EventHandlerDecorator[_SheetPivotTableBeforeDiscardChangesFunc, _SheetPivotTableBeforeDiscardChangesFilter]
3621
+
3622
+ class _ProtectedViewWindowOpenFunc(typing.Protocol):
3623
+ def __call__(self, window): ...
3624
+
3625
+ class _ProtectedViewWindowOpenFilter(typing.Protocol):
3626
+ def __call__(self, window) -> bool: ...
3627
+
3628
+ _ProtectedViewWindowOpenDecorator = _EventHandlerDecorator[_ProtectedViewWindowOpenFunc, _ProtectedViewWindowOpenFilter]
3629
+
3630
+ class _ProtectedViewWindowBeforeEditFunc(typing.Protocol):
3631
+ def __call__(self, window, cancel) -> typing.Optional[bool]: ...
3632
+
3633
+ class _ProtectedViewWindowBeforeEditFilter(typing.Protocol):
3634
+ def __call__(self, window, cancel) -> bool: ...
3635
+
3636
+ _ProtectedViewWindowBeforeEditDecorator = _EventHandlerDecorator[_ProtectedViewWindowBeforeEditFunc, _ProtectedViewWindowBeforeEditFilter]
3637
+
3638
+ class _ProtectedViewWindowBeforeCloseFunc(typing.Protocol):
3639
+ def __call__(self, window, reason, cancel) -> typing.Optional[bool]: ...
3640
+
3641
+ class _ProtectedViewWindowBeforeCloseFilter(typing.Protocol):
3642
+ def __call__(self, window, reason, cancel) -> bool: ...
3643
+
3644
+ _ProtectedViewWindowBeforeCloseDecorator = _EventHandlerDecorator[_ProtectedViewWindowBeforeCloseFunc, _ProtectedViewWindowBeforeCloseFilter]
3645
+
3646
+ class _ProtectedViewWindowResizeFunc(typing.Protocol):
3647
+ def __call__(self, window): ...
3648
+
3649
+ class _ProtectedViewWindowResizeFilter(typing.Protocol):
3650
+ def __call__(self, window) -> bool: ...
3651
+
3652
+ _ProtectedViewWindowResizeDecorator = _EventHandlerDecorator[_ProtectedViewWindowResizeFunc, _ProtectedViewWindowResizeFilter]
3653
+
3654
+ class _ProtectedViewWindowActivateFunc(typing.Protocol):
3655
+ def __call__(self, window): ...
3656
+
3657
+ class _ProtectedViewWindowActivateFilter(typing.Protocol):
3658
+ def __call__(self, window) -> bool: ...
3659
+
3660
+ _ProtectedViewWindowActivateDecorator = _EventHandlerDecorator[_ProtectedViewWindowActivateFunc, _ProtectedViewWindowActivateFilter]
3661
+
3662
+ class _ProtectedViewWindowDeactivateFunc(typing.Protocol):
3663
+ def __call__(self, window): ...
3664
+
3665
+ class _ProtectedViewWindowDeactivateFilter(typing.Protocol):
3666
+ def __call__(self, window) -> bool: ...
3667
+
3668
+ _ProtectedViewWindowDeactivateDecorator = _EventHandlerDecorator[_ProtectedViewWindowDeactivateFunc, _ProtectedViewWindowDeactivateFilter]
3669
+
3670
+ class _WorkbookAfterSaveFunc(typing.Protocol):
3671
+ def __call__(self, workbook, success): ...
3672
+
3673
+ class _WorkbookAfterSaveFilter(typing.Protocol):
3674
+ def __call__(self, workbook, success) -> bool: ...
3675
+
3676
+ _WorkbookAfterSaveDecorator = _EventHandlerDecorator[_WorkbookAfterSaveFunc, _WorkbookAfterSaveFilter]
3677
+
3678
+ class _WorkbookNewChartFunc(typing.Protocol):
3679
+ def __call__(self, workbook, chart): ...
3680
+
3681
+ class _WorkbookNewChartFilter(typing.Protocol):
3682
+ def __call__(self, workbook, chart) -> bool: ...
3683
+
3684
+ _WorkbookNewChartDecorator = _EventHandlerDecorator[_WorkbookNewChartFunc, _WorkbookNewChartFilter]
3685
+
3686
+ @typing.overload
3687
+ def _make_event_handler_decorator(event_name: typing.Literal["NewWorkbook"]) -> _NewWorkbookDecorator: ...
3688
+
3689
+ @typing.overload
3690
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetSelectionChange"]) -> _SheetSelectionChangeDecorator: ...
3691
+
3692
+ @typing.overload
3693
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetBeforeDoubleClick"]) -> _SheetBeforeDoubleClickDecorator: ...
3694
+
3695
+ @typing.overload
3696
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetBeforeRightClick"]) -> _SheetBeforeRightClickDecorator: ...
3697
+
3698
+ @typing.overload
3699
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetActivate"]) -> _SheetActivateDecorator: ...
3700
+
3701
+ @typing.overload
3702
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetDeactivate"]) -> _SheetDeactivateDecorator: ...
3703
+
3704
+ @typing.overload
3705
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetCalculate"]) -> _SheetCalculateDecorator: ...
3706
+
3707
+ @typing.overload
3708
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetChange"]) -> _SheetChangeDecorator: ...
3709
+
3710
+ @typing.overload
3711
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookOpen"]) -> _WorkbookOpenDecorator: ...
3712
+
3713
+ @typing.overload
3714
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookActivate"]) -> _WorkbookActivateDecorator: ...
3715
+
3716
+ @typing.overload
3717
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookDeactivate"]) -> _WorkbookDeactivateDecorator: ...
3718
+
3719
+ @typing.overload
3720
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookBeforeClose"]) -> _WorkbookBeforeCloseDecorator: ...
3721
+
3722
+ @typing.overload
3723
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookBeforeSave"]) -> _WorkbookBeforeSaveDecorator: ...
3724
+
3725
+ @typing.overload
3726
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookBeforePrint"]) -> _WorkbookBeforePrintDecorator: ...
3727
+
3728
+ @typing.overload
3729
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookNewSheet"]) -> _WorkbookNewSheetDecorator: ...
3730
+
3731
+ @typing.overload
3732
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookAddinInstall"]) -> _WorkbookAddinInstallDecorator: ...
3733
+
3734
+ @typing.overload
3735
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookAddinUninstall"]) -> _WorkbookAddinUninstallDecorator: ...
3736
+
3737
+ @typing.overload
3738
+ def _make_event_handler_decorator(event_name: typing.Literal["WindowResize"]) -> _WindowResizeDecorator: ...
3739
+
3740
+ @typing.overload
3741
+ def _make_event_handler_decorator(event_name: typing.Literal["WindowActivate"]) -> _WindowActivateDecorator: ...
3742
+
3743
+ @typing.overload
3744
+ def _make_event_handler_decorator(event_name: typing.Literal["WindowDeactivate"]) -> _WindowDeactivateDecorator: ...
3745
+
3746
+ @typing.overload
3747
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetFollowHyperlink"]) -> _SheetFollowHyperlinkDecorator: ...
3748
+
3749
+ @typing.overload
3750
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetPivotTableUpdate"]) -> _SheetPivotTableUpdateDecorator: ...
3751
+
3752
+ @typing.overload
3753
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookPivotTableCloseConnection"]) -> _WorkbookPivotTableCloseConnectionDecorator: ...
3754
+
3755
+ @typing.overload
3756
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookPivotTableOpenConnection"]) -> _WorkbookPivotTableOpenConnectionDecorator: ...
3757
+
3758
+ @typing.overload
3759
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookSync"]) -> _WorkbookSyncDecorator: ...
3760
+
3761
+ @typing.overload
3762
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookBeforeXmlImport"]) -> _WorkbookBeforeXmlImportDecorator: ...
3763
+
3764
+ @typing.overload
3765
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookAfterXmlImport"]) -> _WorkbookAfterXmlImportDecorator: ...
3766
+
3767
+ @typing.overload
3768
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookBeforeXmlExport"]) -> _WorkbookBeforeXmlExportDecorator: ...
3769
+
3770
+ @typing.overload
3771
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookAfterXmlExport"]) -> _WorkbookAfterXmlExportDecorator: ...
3772
+
3773
+ @typing.overload
3774
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookRowsetComplete"]) -> _WorkbookRowsetCompleteDecorator: ...
3775
+
3776
+ @typing.overload
3777
+ def _make_event_handler_decorator(event_name: typing.Literal["AfterCalculate"]) -> _AfterCalculateDecorator: ...
3778
+
3779
+ @typing.overload
3780
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetPivotTableAfterValueChange"]) -> _SheetPivotTableAfterValueChangeDecorator: ...
3781
+
3782
+ @typing.overload
3783
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetPivotTableBeforeAllocateChanges"]) -> _SheetPivotTableBeforeAllocateChangesDecorator: ...
3784
+
3785
+ @typing.overload
3786
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetPivotTableBeforeCommitChanges"]) -> _SheetPivotTableBeforeCommitChangesDecorator: ...
3787
+
3788
+ @typing.overload
3789
+ def _make_event_handler_decorator(event_name: typing.Literal["SheetPivotTableBeforeDiscardChanges"]) -> _SheetPivotTableBeforeDiscardChangesDecorator: ...
3790
+
3791
+ @typing.overload
3792
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowOpen"]) -> _ProtectedViewWindowOpenDecorator: ...
3793
+
3794
+ @typing.overload
3795
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowBeforeEdit"]) -> _ProtectedViewWindowBeforeEditDecorator: ...
3796
+
3797
+ @typing.overload
3798
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowBeforeClose"]) -> _ProtectedViewWindowBeforeCloseDecorator: ...
3799
+
3800
+ @typing.overload
3801
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowResize"]) -> _ProtectedViewWindowResizeDecorator: ...
3802
+
3803
+ @typing.overload
3804
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowActivate"]) -> _ProtectedViewWindowActivateDecorator: ...
3805
+
3806
+ @typing.overload
3807
+ def _make_event_handler_decorator(event_name: typing.Literal["ProtectedViewWindowDeactivate"]) -> _ProtectedViewWindowDeactivateDecorator: ...
3808
+
3809
+ @typing.overload
3810
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookAfterSave"]) -> _WorkbookAfterSaveDecorator: ...
3811
+
3812
+ @typing.overload
3813
+ def _make_event_handler_decorator(event_name: typing.Literal["WorkbookNewChart"]) -> _WorkbookNewChartDecorator: ...
3814
+
3815
+ def _make_event_handler_decorator(event_name): # type: (str) -> _Decorator
3816
+ """Returns a decorator for registering event handler."""
3817
+ def event_handler_decorator(func=None, filter=None, com_package=None):
3818
+ if func is None:
3819
+ return xl_event(event_name, filter=filter, com_package=com_package)
3820
+ return xl_event(event_name, filter=filter, com_package=com_package)(func)
3821
+ return event_handler_decorator
3822
+
3823
+ class xl_event:
3824
+ """Namespace for Excel event handler decorators.
3825
+
3826
+ For example, the following registers an event handler to be called whenever a new
3827
+ workbook is created::
3828
+
3829
+ @xl_event.new_workbook
3830
+ def on_new_workbook(workbook):
3831
+ pass
3832
+
3833
+ Excel objects are passed as Python COM wrappers, and the package used for the wrappers
3834
+ can be set using the optional 'com_package' keyword argument to the decorator. By
3835
+ default, 'win32com' is used.
3836
+
3837
+ To use 'comtypes' instead of 'win32com' use ``com_package="comtypes", for example::
3838
+
3839
+ @xl_event.new_workbook(com_package="comtypes")
3840
+ def on_new_workbook(workbook):
3841
+ # 'workbook' is a comtypes Python COM wrapper object
3842
+ pass
3843
+
3844
+ An xl_event instance can also be used as a decorator directly. For example, the below
3845
+ is equivalent to the above example::
3846
+
3847
+ @xl_event("NewWorkbook")
3848
+ def on_new_workbook(workbook):
3849
+ pass
3850
+
3851
+ Some events take a 'cancel' argument, which the handler can set to cancel the action
3852
+ the event is reporting. As in VBA, 'cancel' is passed whatever value was left by any
3853
+ handler called before this one, and the handler sets it by returning a bool::
3854
+
3855
+ @xl_event.workbook_before_close
3856
+ def on_workbook_before_close(workbook, cancel):
3857
+ # Returning True is the same as setting Cancel = True in VBA
3858
+ return True
3859
+
3860
+ Returning anything other than a bool, including None, leaves 'cancel' as it was.
3861
+ """
3862
+
3863
+ def __init__(self, event_name, filter=None, com_package=None):
3864
+ """Don't use directly, use one of the class attributes instead."""
3865
+ self.__event_name = event_name
3866
+ self.__filter = filter
3867
+ self.__com_package = com_package
3868
+
3869
+ def __call__(self, func): # type: (_Function) -> _Function
3870
+ """Called as a decorator the function to be registered as the event handler."""
3871
+ # Add the filter decorator to the event handler function as a new function attribute.
3872
+ def make_filter_decorator(event_handler):
3873
+ def filter_decorator(func):
3874
+ event_handler.__pyxll_event_filter__ = func
3875
+ return func
3876
+ return filter_decorator
3877
+ func.filter = make_filter_decorator(func) # type: ignore
3878
+
3879
+ # The event handler doesn't get registered when not running in Excel.
3880
+ return func
3881
+
3882
+ new_workbook = staticmethod(_make_event_handler_decorator("NewWorkbook"))
3883
+ sheet_selection_change = staticmethod(_make_event_handler_decorator("SheetSelectionChange"))
3884
+ sheet_before_double_click = staticmethod(_make_event_handler_decorator("SheetBeforeDoubleClick"))
3885
+ sheet_before_right_click = staticmethod(_make_event_handler_decorator("SheetBeforeRightClick"))
3886
+ sheet_activate = staticmethod(_make_event_handler_decorator("SheetActivate"))
3887
+ sheet_deactivate = staticmethod(_make_event_handler_decorator("SheetDeactivate"))
3888
+ sheet_calculate = staticmethod(_make_event_handler_decorator("SheetCalculate"))
3889
+ sheet_change = staticmethod(_make_event_handler_decorator("SheetChange"))
3890
+ workbook_open = staticmethod(_make_event_handler_decorator("WorkbookOpen"))
3891
+ workbook_activate = staticmethod(_make_event_handler_decorator("WorkbookActivate"))
3892
+ workbook_deactivate = staticmethod(_make_event_handler_decorator("WorkbookDeactivate"))
3893
+ workbook_before_close = staticmethod(_make_event_handler_decorator("WorkbookBeforeClose"))
3894
+ workbook_before_save = staticmethod(_make_event_handler_decorator("WorkbookBeforeSave"))
3895
+ workbook_before_print = staticmethod(_make_event_handler_decorator("WorkbookBeforePrint"))
3896
+ workbook_new_sheet = staticmethod(_make_event_handler_decorator("WorkbookNewSheet"))
3897
+ workbook_addin_install = staticmethod(_make_event_handler_decorator("WorkbookAddinInstall"))
3898
+ workbook_addin_uninstall = staticmethod(_make_event_handler_decorator("WorkbookAddinUninstall"))
3899
+ window_resize = staticmethod(_make_event_handler_decorator("WindowResize"))
3900
+ window_activate = staticmethod(_make_event_handler_decorator("WindowActivate"))
3901
+ window_deactivate = staticmethod(_make_event_handler_decorator("WindowDeactivate"))
3902
+ sheet_follow_hyperlink = staticmethod(_make_event_handler_decorator("SheetFollowHyperlink"))
3903
+ sheet_pivot_table_update = staticmethod(_make_event_handler_decorator("SheetPivotTableUpdate"))
3904
+ workbook_pivot_table_close_connection = staticmethod(_make_event_handler_decorator("WorkbookPivotTableCloseConnection"))
3905
+ workbook_pivot_table_open_connection = staticmethod(_make_event_handler_decorator("WorkbookPivotTableOpenConnection"))
3906
+ workbook_sync = staticmethod(_make_event_handler_decorator("WorkbookSync"))
3907
+ workbook_before_xml_import = staticmethod(_make_event_handler_decorator("WorkbookBeforeXmlImport"))
3908
+ workbook_after_xml_import = staticmethod(_make_event_handler_decorator("WorkbookAfterXmlImport"))
3909
+ workbook_before_xml_export = staticmethod(_make_event_handler_decorator("WorkbookBeforeXmlExport"))
3910
+ workbook_after_xml_export = staticmethod(_make_event_handler_decorator("WorkbookAfterXmlExport"))
3911
+ workbook_rowset_complete = staticmethod(_make_event_handler_decorator("WorkbookRowsetComplete"))
3912
+ after_calculate = staticmethod(_make_event_handler_decorator("AfterCalculate"))
3913
+ sheet_pivot_table_after_value_change = staticmethod(_make_event_handler_decorator("SheetPivotTableAfterValueChange"))
3914
+ sheet_pivot_table_before_allocate_changes = staticmethod(_make_event_handler_decorator("SheetPivotTableBeforeAllocateChanges"))
3915
+ sheet_pivot_table_before_commit_changes = staticmethod(_make_event_handler_decorator("SheetPivotTableBeforeCommitChanges"))
3916
+ sheet_pivot_table_before_discard_changes = staticmethod(_make_event_handler_decorator("SheetPivotTableBeforeDiscardChanges"))
3917
+ protected_view_window_open = staticmethod(_make_event_handler_decorator("ProtectedViewWindowOpen"))
3918
+ protected_view_window_before_edit = staticmethod(_make_event_handler_decorator("ProtectedViewWindowBeforeEdit"))
3919
+ protected_view_window_before_close = staticmethod(_make_event_handler_decorator("ProtectedViewWindowBeforeClose"))
3920
+ protected_view_window_resize = staticmethod(_make_event_handler_decorator("ProtectedViewWindowResize"))
3921
+ protected_view_window_activate = staticmethod(_make_event_handler_decorator("ProtectedViewWindowActivate"))
3922
+ protected_view_window_deactivate = staticmethod(_make_event_handler_decorator("ProtectedViewWindowDeactivate"))
3923
+ workbook_after_save = staticmethod(_make_event_handler_decorator("WorkbookAfterSave"))
3924
+ workbook_new_chart = staticmethod(_make_event_handler_decorator("WorkbookNewChart"))