pyxll 5.9.0__cp313-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 +2720 -0
- pyxll/__main__.py +5 -0
- pyxll/_activate.py +158 -0
- pyxll/_admin.py +455 -0
- pyxll/_cert.py +152 -0
- pyxll/_check.py +241 -0
- pyxll/_cli.py +161 -0
- pyxll/_config.py +121 -0
- pyxll/_errors.py +16 -0
- pyxll/_install.py +348 -0
- pyxll/_uninstall.py +75 -0
- pyxll/_update.py +281 -0
- pyxll/_utils.py +1386 -0
- pyxll/py.typed +0 -0
- pyxll/pyxll.crt +36 -0
- pyxll-5.9.0.dist-info/DESCRIPTION.rst +10 -0
- pyxll-5.9.0.dist-info/METADATA +110 -0
- pyxll-5.9.0.dist-info/RECORD +22 -0
- pyxll-5.9.0.dist-info/WHEEL +4 -0
- pyxll-5.9.0.dist-info/entry_points.txt +2 -0
- pyxll-5.9.0.dist-info/metadata.json +23 -0
- pyxll-5.9.0.dist-info/top_level.txt +1 -0
pyxll/__init__.py
ADDED
|
@@ -0,0 +1,2720 @@
|
|
|
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
|
+
_log = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from xml.dom import minidom
|
|
31
|
+
_have_minidom = True
|
|
32
|
+
except ImportError:
|
|
33
|
+
minidom = None # type: ignore
|
|
34
|
+
|
|
35
|
+
__version__ = "5.9.0"
|
|
36
|
+
|
|
37
|
+
nan = 1e10000 * 0
|
|
38
|
+
|
|
39
|
+
xlCalculationAutomatic = 1
|
|
40
|
+
xlCalculationSemiAutomatic = 2
|
|
41
|
+
xlCalculationManual = 3
|
|
42
|
+
|
|
43
|
+
xlDialogTypeNone = 0
|
|
44
|
+
xlDialogTypeFunctionWizard = 1
|
|
45
|
+
xlDialogTypeSearchAndReplace = 2
|
|
46
|
+
|
|
47
|
+
_no_value = object()
|
|
48
|
+
|
|
49
|
+
# Import typing for use by some type hints
|
|
50
|
+
if sys.version_info[:2] > (3, 5):
|
|
51
|
+
try:
|
|
52
|
+
import typing
|
|
53
|
+
if typing.TYPE_CHECKING:
|
|
54
|
+
from typing import Any, Tuple, Type, Union, Callable
|
|
55
|
+
from typing import TypeAlias # type: ignore
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
import exceltypes # type: ignore
|
|
59
|
+
except ImportError:
|
|
60
|
+
pass
|
|
61
|
+
try:
|
|
62
|
+
import win32com.client # type: ignore
|
|
63
|
+
except ImportError:
|
|
64
|
+
pass
|
|
65
|
+
try:
|
|
66
|
+
import pythoncom # type: ignore
|
|
67
|
+
except ImportError:
|
|
68
|
+
pass
|
|
69
|
+
try:
|
|
70
|
+
import comtypes # type: ignore
|
|
71
|
+
except ImportError:
|
|
72
|
+
pass
|
|
73
|
+
try:
|
|
74
|
+
import types
|
|
75
|
+
except ImportError:
|
|
76
|
+
pass
|
|
77
|
+
try:
|
|
78
|
+
import configparser
|
|
79
|
+
except ImportError:
|
|
80
|
+
pass
|
|
81
|
+
try:
|
|
82
|
+
import concurrent
|
|
83
|
+
except ImportError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
_ExcInfo = "Tuple[Type[BaseException], BaseException, types.TracebackType]" # type: TypeAlias
|
|
87
|
+
_OptExcInfo = "Union[_ExcInfo, Tuple[None, None, None]]" # type: TypeAlias
|
|
88
|
+
_COMObject = "Union[win32com.client.Dispatch, pythoncom.PyIUnknown, comtypes.POINTER, Any]" # type: TypeAlias
|
|
89
|
+
_ExcelApplication = "Union[exceltypes.Application, _COMObject]" # type: TypeAlias
|
|
90
|
+
_ExcelRange = "Union[exceltypes.Range, _COMObject]" # type: TypeAlias
|
|
91
|
+
_Function = "Callable[..., typing.Any]" # type: TypeAlias
|
|
92
|
+
_Decorator = "Union[Callable[[_Function], _Function], _Function]" # type: TypeAlias
|
|
93
|
+
except ImportError:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
def reload():
|
|
97
|
+
"""
|
|
98
|
+
Causes the PyXLL addin and any modules listed in the config file to be reloaded
|
|
99
|
+
once the calling function has returned control back to Excel.
|
|
100
|
+
|
|
101
|
+
If the `deep_reload` configuration option is turned on then any dependencies
|
|
102
|
+
of the modules listed in the config file will also be reloaded.
|
|
103
|
+
|
|
104
|
+
The Python interpreter is not restarted.
|
|
105
|
+
"""
|
|
106
|
+
raise Exception("Not supported when running outside of Excel")
|
|
107
|
+
|
|
108
|
+
def com_reload():
|
|
109
|
+
"""
|
|
110
|
+
Causes the COM part of the PyXLL addin to be reloaded once the calling function
|
|
111
|
+
has returned control back to Excel.
|
|
112
|
+
|
|
113
|
+
This doesn't reload any Python modules or rebind any functions. The COM addin
|
|
114
|
+
is responsible for the ribbon user interface and reloading it will cause the
|
|
115
|
+
ribbon to be reloaded.
|
|
116
|
+
"""
|
|
117
|
+
raise Exception("Not supported when running outside of Excel")
|
|
118
|
+
|
|
119
|
+
def rebind():
|
|
120
|
+
"""
|
|
121
|
+
Causes the PyXLL addin to rebuild the bindings between the exposed Python
|
|
122
|
+
functions and Excel once the calling function has returned control back to Excel.
|
|
123
|
+
|
|
124
|
+
This can be useful when importing modules or declaring new Python functions
|
|
125
|
+
dynamically and you want newly imported or created Python functions to be exposed to Excel without reloading.
|
|
126
|
+
|
|
127
|
+
Example usage::
|
|
128
|
+
|
|
129
|
+
from pyxll import xl_macro, rebind
|
|
130
|
+
|
|
131
|
+
@xl_macro
|
|
132
|
+
def load_python_modules():
|
|
133
|
+
import another_module_with_pyxll_functions
|
|
134
|
+
rebind()
|
|
135
|
+
"""
|
|
136
|
+
raise Exception("Not supported when running outside of Excel")
|
|
137
|
+
|
|
138
|
+
def about():
|
|
139
|
+
"""
|
|
140
|
+
Show the PyXLL 'about' dialog.
|
|
141
|
+
"""
|
|
142
|
+
raise Exception("Not supported when running outside of Excel")
|
|
143
|
+
|
|
144
|
+
def xl_arg_type(name, # type: str
|
|
145
|
+
base_type, # type: str
|
|
146
|
+
allow_arrays=True, # type: bool
|
|
147
|
+
macro=None, # type: typing.Union[bool, None]
|
|
148
|
+
thread_safe=None, # type: typing.Union[bool, None]
|
|
149
|
+
typing_type=None # type: typing.Union[typing.Type, None]
|
|
150
|
+
): # type: (...) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Callable[..., typing.Any]]
|
|
151
|
+
"""
|
|
152
|
+
Decorator for adding custom types for use with
|
|
153
|
+
functions exposed via xl_func and xl_macro.
|
|
154
|
+
eg:
|
|
155
|
+
|
|
156
|
+
class myobject:
|
|
157
|
+
def __init__(self, name):
|
|
158
|
+
self.name = name
|
|
159
|
+
|
|
160
|
+
@xl_arg_type("myobject", "string")
|
|
161
|
+
def myobject_from_string(name):
|
|
162
|
+
return myobject(name)
|
|
163
|
+
|
|
164
|
+
@xl_func("myobject obj: string")
|
|
165
|
+
def get_name(obj):
|
|
166
|
+
return obj.name
|
|
167
|
+
|
|
168
|
+
in this example, get_name is called from excel with a string argument
|
|
169
|
+
that is converted to a myobject instance via myobject_from_string.
|
|
170
|
+
|
|
171
|
+
If allow_arrays is True, arrays of the custom type are allowed
|
|
172
|
+
using the standard signature notation 'myobject[]' (for the example
|
|
173
|
+
above).
|
|
174
|
+
|
|
175
|
+
macro and thread_safe can be set if the function using this type
|
|
176
|
+
must be a macro equivalent function (set macro=True) or must not
|
|
177
|
+
be registered as thread safe (set thread_safe=False).
|
|
178
|
+
"""
|
|
179
|
+
def dummy_decorator(func):
|
|
180
|
+
return func
|
|
181
|
+
return dummy_decorator
|
|
182
|
+
|
|
183
|
+
def xl_return_type(name, # type: str
|
|
184
|
+
base_type, # type: str
|
|
185
|
+
allow_arrays=True, # type: bool
|
|
186
|
+
macro=None, # type: typing.Union[bool, None]
|
|
187
|
+
thread_safe=None, # type: typing.Union[bool, None]
|
|
188
|
+
typing_type=None # type: typing.Union[typing.Type, None]
|
|
189
|
+
): # type: (...) -> _Decorator
|
|
190
|
+
"""
|
|
191
|
+
Decorator for adding custom types for use with
|
|
192
|
+
functions exposed via xl_func and xl_macro.
|
|
193
|
+
eg:
|
|
194
|
+
|
|
195
|
+
class myobject:
|
|
196
|
+
def __init__(self, name):
|
|
197
|
+
self.name = name
|
|
198
|
+
|
|
199
|
+
@xl_return_type("myobject", "string")
|
|
200
|
+
def myobject_to_string(obj):
|
|
201
|
+
return obj.name
|
|
202
|
+
|
|
203
|
+
@xl_func("string name: myobject")
|
|
204
|
+
def get_object(name):
|
|
205
|
+
return myobject(name)
|
|
206
|
+
|
|
207
|
+
in this example, get_object is called from excel with a string
|
|
208
|
+
argument and returns a myobject instance. That is converted to a
|
|
209
|
+
string by the registered myobject_to_string function and returned
|
|
210
|
+
to excel as a string.
|
|
211
|
+
|
|
212
|
+
If allow_arrays is True, arrays of the custom type are allowed
|
|
213
|
+
using the standard signature notation 'myobject[]' (for the example
|
|
214
|
+
above).
|
|
215
|
+
|
|
216
|
+
macro and thread_safe can be set if the function using this type
|
|
217
|
+
must be a macro equivalent function (set macro=True) or must not
|
|
218
|
+
be registered as thread safe (set thread_safe=False).
|
|
219
|
+
"""
|
|
220
|
+
def dummy_decorator(func):
|
|
221
|
+
return func
|
|
222
|
+
return dummy_decorator
|
|
223
|
+
|
|
224
|
+
def xl_return(_type=None, # type: typing.Union[str, None]
|
|
225
|
+
**kwargs):
|
|
226
|
+
# type: (...) -> _Decorator
|
|
227
|
+
"""
|
|
228
|
+
Add type information for a function's return type.
|
|
229
|
+
|
|
230
|
+
This can be used instead or as well as providing the return type information
|
|
231
|
+
in the function signature.
|
|
232
|
+
|
|
233
|
+
Using this decorator can be simpler when the return type is generic and requires
|
|
234
|
+
complex type arguments.
|
|
235
|
+
|
|
236
|
+
@xl_func
|
|
237
|
+
@xl_return("dataframe", index=True, columns=True)
|
|
238
|
+
def return_pandas_dataframe():
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
:param _type: Type expected to be returned by the function
|
|
242
|
+
:param kwargs: Keyword arguments provided to the return type converter
|
|
243
|
+
"""
|
|
244
|
+
def dummy_decorator(func):
|
|
245
|
+
return func
|
|
246
|
+
return dummy_decorator
|
|
247
|
+
|
|
248
|
+
def xl_arg(_name, # type: str
|
|
249
|
+
_type=None, # type: typing.Union[str, None]
|
|
250
|
+
_label=None, # type: typing.Union[str, None]
|
|
251
|
+
_description=None, # type: typing.Union[str, None]
|
|
252
|
+
**kwargs):
|
|
253
|
+
# type: (...) -> _Decorator
|
|
254
|
+
"""
|
|
255
|
+
Add type information for a function's argument type.
|
|
256
|
+
|
|
257
|
+
This can be used instead or as well as providing the return type information
|
|
258
|
+
in the function signature.
|
|
259
|
+
|
|
260
|
+
Using this decorator can be simpler when the return type is generic and requires
|
|
261
|
+
complex type arguments.
|
|
262
|
+
|
|
263
|
+
@xl_func
|
|
264
|
+
@xl_arg("x", "dataframe", index=True, columns=True)
|
|
265
|
+
def return_pandas_dataframe(x):
|
|
266
|
+
pass
|
|
267
|
+
|
|
268
|
+
:param _name: Name of the argument this relates to.
|
|
269
|
+
:param _type: Type expected for the argument.
|
|
270
|
+
:param _label: Label to show in Excel function help for the argument.
|
|
271
|
+
:param _description: Argument description to show in Excel function help for the argument.
|
|
272
|
+
:param kwargs: Keyword arguments provided to the argument type converter.
|
|
273
|
+
"""
|
|
274
|
+
def dummy_decorator(func):
|
|
275
|
+
return func
|
|
276
|
+
return dummy_decorator
|
|
277
|
+
|
|
278
|
+
def get_type_converter(src_type, # type: typing.Union[str, typing.Type]
|
|
279
|
+
dest_type, # type: typing.Union[str, typing.Type]
|
|
280
|
+
src_kwargs={}, # type: typing.Dict[str, typing.Any]
|
|
281
|
+
dest_kwargs={} # type: typing.Dict[str, typing.Any]
|
|
282
|
+
): # type: (...) -> typing.Callable[[typing.Any], typing.Any]
|
|
283
|
+
"""
|
|
284
|
+
Return a function that converts from one type registered
|
|
285
|
+
with PyXLL to another.
|
|
286
|
+
|
|
287
|
+
When this function is called from outside of Excel then it
|
|
288
|
+
is purely a stub function. It returns a dummy function that simply
|
|
289
|
+
returns the argument it is passed.
|
|
290
|
+
|
|
291
|
+
This is so the functions can be written that take var arguments when
|
|
292
|
+
called from Excel and use PyXLL's type conversion to convert to proper
|
|
293
|
+
python types, but accept proper python types when called from other python
|
|
294
|
+
code outside of Excel (e.g. when testing in an interactive prompt or in
|
|
295
|
+
unit tests).
|
|
296
|
+
|
|
297
|
+
For example::
|
|
298
|
+
|
|
299
|
+
@xl_func("var a_date: var")
|
|
300
|
+
def test_func(a_date):
|
|
301
|
+
if a_date is not None:
|
|
302
|
+
var_to_date = get_type_converter("var", "date")
|
|
303
|
+
a_date = var_to_date(a_date) # does nothing if not called in Excel
|
|
304
|
+
return a_date.strftime("%Y-%m-%d")
|
|
305
|
+
|
|
306
|
+
>> test_func(datetime.date(2014,2,11))
|
|
307
|
+
'2014-02-11'
|
|
308
|
+
"""
|
|
309
|
+
# This is a dummy function here only so it can be imported and does not perform
|
|
310
|
+
# any type conversion when no imported from inside Excel.
|
|
311
|
+
return lambda x: x
|
|
312
|
+
|
|
313
|
+
def get_active_object():
|
|
314
|
+
# type: () -> _ExcelApplication
|
|
315
|
+
"""
|
|
316
|
+
Deprecated. Use xl_app instead.
|
|
317
|
+
"""
|
|
318
|
+
warnings.warn("pyxll.get_active_object is deprecated. Use xl_app instead.", DeprecationWarning)
|
|
319
|
+
|
|
320
|
+
# this is only used when calling from outside Excel.
|
|
321
|
+
# the builtin pyxll module does 'the right thing'.
|
|
322
|
+
xl = xl_app()
|
|
323
|
+
return xl.Windows[0]
|
|
324
|
+
|
|
325
|
+
def xl_app(com_package="win32com"):
|
|
326
|
+
# type: (typing.Union[str, None]) -> _ExcelApplication
|
|
327
|
+
"""
|
|
328
|
+
Return the COM Excel Application object for the Excel
|
|
329
|
+
instance the PyXLL addin is running in.
|
|
330
|
+
|
|
331
|
+
When called from outside of Excel, this will return the first
|
|
332
|
+
open Excel found. If there is no Excel window open, this
|
|
333
|
+
function will raise and Exception.
|
|
334
|
+
"""
|
|
335
|
+
# this is only used when calling from outside Excel.
|
|
336
|
+
# the builtin pyxll module does 'the right thing'.
|
|
337
|
+
if com_package == "pythoncom":
|
|
338
|
+
import pythoncom # type: ignore
|
|
339
|
+
return pythoncom.GetActiveObject("Excel.Application")
|
|
340
|
+
|
|
341
|
+
elif com_package == "win32com":
|
|
342
|
+
import pythoncom # type: ignore
|
|
343
|
+
xl = pythoncom.GetActiveObject("Excel.Application")
|
|
344
|
+
return _wrap_iunknown(xl)
|
|
345
|
+
|
|
346
|
+
elif com_package == "comtypes":
|
|
347
|
+
import comtypes.client # type: ignore
|
|
348
|
+
return comtypes.client.GetActiveObject("Excel.Application")
|
|
349
|
+
|
|
350
|
+
elif com_package == "xlwings":
|
|
351
|
+
import xlwings # type: ignore
|
|
352
|
+
try:
|
|
353
|
+
version = tuple(map(int, xlwings.__version__.split(".")[:2]))
|
|
354
|
+
except Exception:
|
|
355
|
+
_log.warning("Error parsing xlwings version '%s'" % xlwings.__version__)
|
|
356
|
+
version = (0, 0)
|
|
357
|
+
assert version >= (0, 9), "xlwings >= 0.9 required (%s is installed)" % xlwings.__version__
|
|
358
|
+
if xlwings.apps.count == 0:
|
|
359
|
+
return xlwings.App()
|
|
360
|
+
return xlwings.apps.active
|
|
361
|
+
|
|
362
|
+
else:
|
|
363
|
+
raise ValueError("Unexpected com_package '%s'" % com_package)
|
|
364
|
+
|
|
365
|
+
def get_dialog_type():
|
|
366
|
+
# type: () -> int
|
|
367
|
+
"""
|
|
368
|
+
Returns a value indicating what type of dialog a function was
|
|
369
|
+
called from, if any.
|
|
370
|
+
|
|
371
|
+
This can be used to disable slow running calculations in the
|
|
372
|
+
function wizard or when doing a search and replace operation.
|
|
373
|
+
"""
|
|
374
|
+
return xlDialogTypeNone
|
|
375
|
+
|
|
376
|
+
def get_last_error(cell):
|
|
377
|
+
# type: (Union[XLCell, exceltypes.Range]) -> _OptExcInfo
|
|
378
|
+
"""
|
|
379
|
+
When a Python function is called from an Excel worksheet, if an uncaught exception is raised PyXLL
|
|
380
|
+
caches the exception and traceback as well as logging it to the log file.
|
|
381
|
+
|
|
382
|
+
The last exception raised while evaluating a cell can be retrieved using this function.
|
|
383
|
+
|
|
384
|
+
The cache used by PyXLL to store thrown exceptions is limited to a maximum size, and so if there are
|
|
385
|
+
more cells with errors than the cache size the least recently thrown exceptions are discarded. The
|
|
386
|
+
cache size may be set via the error_cache_size setting in the config file.
|
|
387
|
+
|
|
388
|
+
When a cell returns a value and no exception is thrown any previous error is **not** discarded. This
|
|
389
|
+
is because doing so would add additional performance overhead to every function call.
|
|
390
|
+
|
|
391
|
+
:param xl_cell: XLCell instance or a COM Range object (the exact type depends
|
|
392
|
+
on the com_package setting in the config file.
|
|
393
|
+
|
|
394
|
+
:return: The last exception raised by a Python function evaluated in the cell, as a tuple
|
|
395
|
+
(type, value, traceback).
|
|
396
|
+
|
|
397
|
+
Example usage::
|
|
398
|
+
|
|
399
|
+
from pyxll import xl_func, xl_menu, xl_version, get_last_error
|
|
400
|
+
import traceback
|
|
401
|
+
|
|
402
|
+
@xl_func("xl_cell: string")
|
|
403
|
+
def python_error(cell):
|
|
404
|
+
exc_type, exc_value, exc_traceback = pyxll.get_last_error(cell)
|
|
405
|
+
if exc_type is None:
|
|
406
|
+
return "No error"
|
|
407
|
+
|
|
408
|
+
return "".join(traceback.format_exception_only(exc_type, exc_value))
|
|
409
|
+
"""
|
|
410
|
+
raise Exception("Not supported when running outside of Excel")
|
|
411
|
+
|
|
412
|
+
def cached_object_count():
|
|
413
|
+
# type: () -> int
|
|
414
|
+
"""Return the number of objects cached in the internal object cache"""
|
|
415
|
+
return 0
|
|
416
|
+
|
|
417
|
+
def message_box(message, caption="", flags=0):
|
|
418
|
+
# type: (str, str, int) -> None
|
|
419
|
+
"""Show a message dialog box."""
|
|
420
|
+
import win32api # type: ignore
|
|
421
|
+
return win32api.MessageBox(None, message, caption, flags)
|
|
422
|
+
|
|
423
|
+
def xlfGetDocument(arg_num, name=None):
|
|
424
|
+
raise Exception("Not supported when running outside of Excel")
|
|
425
|
+
|
|
426
|
+
def xlfGetWorkspace(arg_num):
|
|
427
|
+
raise Exception("Not supported when running outside of Excel")
|
|
428
|
+
|
|
429
|
+
def xlfGetWorkbook(arg_num, workbook_name=None):
|
|
430
|
+
raise Exception("Not supported when running outside of Excel")
|
|
431
|
+
|
|
432
|
+
def xlfGetWindow(arg_num, workbook_name=None):
|
|
433
|
+
raise Exception("Not supported when running outside of Excel")
|
|
434
|
+
|
|
435
|
+
def xlfWindows(match_type=None, mask=None):
|
|
436
|
+
raise Exception("Not supported when running outside of Excel")
|
|
437
|
+
|
|
438
|
+
def xlfCaller():
|
|
439
|
+
# type: () -> XLCell
|
|
440
|
+
raise Exception("Not supported when running outside of Excel")
|
|
441
|
+
|
|
442
|
+
def xlAsyncReturn(async_handle, value):
|
|
443
|
+
raise Exception("Not supported when running outside of Excel")
|
|
444
|
+
|
|
445
|
+
def xlcAlert(message):
|
|
446
|
+
# type: (str) -> None
|
|
447
|
+
raise Exception("Not supported when running outside of Excel")
|
|
448
|
+
|
|
449
|
+
def xlcCalculation(calculation_type):
|
|
450
|
+
raise Exception("Not supported when running outside of Excel")
|
|
451
|
+
|
|
452
|
+
def xlcCalculateNow():
|
|
453
|
+
raise Exception("Not supported when running outside of Excel")
|
|
454
|
+
|
|
455
|
+
def xlcCalculateDocument():
|
|
456
|
+
raise Exception("Not supported when running outside of Excel")
|
|
457
|
+
|
|
458
|
+
def xlAbort(retain=True):
|
|
459
|
+
raise Exception("Not supported when running outside of Excel")
|
|
460
|
+
|
|
461
|
+
def xlSheetNm(sheet_id):
|
|
462
|
+
raise Exception("Not supported when running outside of Excel")
|
|
463
|
+
|
|
464
|
+
def xlSheetId(sheet_name):
|
|
465
|
+
raise Exception("Not supported when running outside of Excel")
|
|
466
|
+
|
|
467
|
+
def xlfVolatile(volatile):
|
|
468
|
+
# has no effect when running outside of Excel
|
|
469
|
+
pass
|
|
470
|
+
|
|
471
|
+
class XLAsyncHandle(object):
|
|
472
|
+
caller = None
|
|
473
|
+
function_name = None
|
|
474
|
+
|
|
475
|
+
def __init__(self, *args, **kwargs):
|
|
476
|
+
raise Exception("Not supported when running outside of Excel")
|
|
477
|
+
|
|
478
|
+
def set_value(self, value):
|
|
479
|
+
raise Exception("Not supported when running outside of Excel")
|
|
480
|
+
|
|
481
|
+
def set_error(self,
|
|
482
|
+
exc_type, # type: Type[BaseException]
|
|
483
|
+
exc_value, # type: BaseException
|
|
484
|
+
exc_traceback # type: types.TracebackType
|
|
485
|
+
):
|
|
486
|
+
raise Exception("Not supported when running outside of Excel")
|
|
487
|
+
|
|
488
|
+
if sys.version_info[:3] >= (3, 5, 1):
|
|
489
|
+
import asyncio
|
|
490
|
+
|
|
491
|
+
def get_event_loop():
|
|
492
|
+
# type: () -> asyncio.AbstractEventLoop
|
|
493
|
+
"""
|
|
494
|
+
Get the async event loop used by PyXLL for scheduling async tasks.
|
|
495
|
+
|
|
496
|
+
If called in Excel and the event loop is not already running it is
|
|
497
|
+
started in a background thread.
|
|
498
|
+
|
|
499
|
+
If called outside of Excel then the event loop is returned
|
|
500
|
+
without starting it.
|
|
501
|
+
|
|
502
|
+
:return: asyncio.AbstractEventLoop
|
|
503
|
+
"""
|
|
504
|
+
return asyncio.get_event_loop()
|
|
505
|
+
|
|
506
|
+
class RTD(object):
|
|
507
|
+
def __init__(self, value=None):
|
|
508
|
+
self.__value = value
|
|
509
|
+
self.__error = None
|
|
510
|
+
|
|
511
|
+
def __get_value(self):
|
|
512
|
+
return self.__value
|
|
513
|
+
|
|
514
|
+
def __set_value(self, value):
|
|
515
|
+
self.__value = value
|
|
516
|
+
self.__error = None
|
|
517
|
+
|
|
518
|
+
value = property(__get_value, __set_value)
|
|
519
|
+
|
|
520
|
+
def connect(self):
|
|
521
|
+
"""Called when Excel connects to this RTD instance, which occurs shortly after an
|
|
522
|
+
Excel function has returned an RTD object.
|
|
523
|
+
|
|
524
|
+
May be overridden in the sub-class.
|
|
525
|
+
|
|
526
|
+
Since PyXLL 4.2.0: May be an async method.
|
|
527
|
+
"""
|
|
528
|
+
pass
|
|
529
|
+
|
|
530
|
+
def disconnect(self):
|
|
531
|
+
"""Called when Excel no longer needs the RTD instance. This is usually because there are no longer
|
|
532
|
+
any cells that need it or because Excel is shutting down.
|
|
533
|
+
|
|
534
|
+
May be overridden in the sub-class.
|
|
535
|
+
|
|
536
|
+
Since PyXLL 4.2.0: May be an async method.
|
|
537
|
+
"""
|
|
538
|
+
pass
|
|
539
|
+
|
|
540
|
+
@property
|
|
541
|
+
def connected(self):
|
|
542
|
+
return False
|
|
543
|
+
|
|
544
|
+
@property
|
|
545
|
+
def disconnected(self):
|
|
546
|
+
return False
|
|
547
|
+
|
|
548
|
+
def set_error(self,
|
|
549
|
+
exc_type, # type: typing.Type[BaseException]
|
|
550
|
+
exc_value, # type: BaseException
|
|
551
|
+
exc_traceback # type: types.TracebackType
|
|
552
|
+
):
|
|
553
|
+
"""Update Excel with an error. E.g.::
|
|
554
|
+
|
|
555
|
+
def update(self):
|
|
556
|
+
try:
|
|
557
|
+
self.value = get_new_value()
|
|
558
|
+
except:
|
|
559
|
+
self.set_error(*sys.exc_info())
|
|
560
|
+
"""
|
|
561
|
+
self.__error = (exc_type, exc_value, exc_traceback)
|
|
562
|
+
|
|
563
|
+
class XLCell(object):
|
|
564
|
+
|
|
565
|
+
value = None # type: typing.Any
|
|
566
|
+
|
|
567
|
+
def __init__(self, *args, **kwargs):
|
|
568
|
+
raise Exception("Not supported when running outside of Excel")
|
|
569
|
+
|
|
570
|
+
@staticmethod
|
|
571
|
+
def from_range(range):
|
|
572
|
+
# type: (typing.Union[_ExcelRange, str]) -> XLCell
|
|
573
|
+
raise Exception("Not supported when running outside of Excel")
|
|
574
|
+
|
|
575
|
+
def to_range(self, com_package=None):
|
|
576
|
+
# type: (typing.Union[str, None]) -> _ExcelRange
|
|
577
|
+
"""Return an Excel.Range object using the COM package specified.
|
|
578
|
+
:param com_package: COM package to use to return the COM Range object.
|
|
579
|
+
May be any of:
|
|
580
|
+
- win32com
|
|
581
|
+
- comtypes
|
|
582
|
+
- xlwings
|
|
583
|
+
"""
|
|
584
|
+
raise Exception("Not supported when running outside of Excel")
|
|
585
|
+
|
|
586
|
+
def options(self,
|
|
587
|
+
type=None, # type: typing.Union[str, typing.Type, None]
|
|
588
|
+
auto_resize=None, # type: typing.Union[bool, None]
|
|
589
|
+
type_kwargs=None, # type: typing.Union[typing.Dict[str, typing.Any], None]
|
|
590
|
+
formatter=None, # type: typing.Union[BaseFormatter, None]
|
|
591
|
+
nan_value=_no_value, # type: typing.Any
|
|
592
|
+
posinf_value=_no_value, # type: typing.Any
|
|
593
|
+
neginf_value=_no_value # type: typing.Any
|
|
594
|
+
): # type: (...) -> XLCell
|
|
595
|
+
"""Set options that control how values are retrieved and set.
|
|
596
|
+
|
|
597
|
+
:param type: Type to convert values to when getting.
|
|
598
|
+
:param auto_resize: If True, auto-resize when setting arrays.
|
|
599
|
+
:param type_kwargs: Options for type converter.
|
|
600
|
+
:param formatter: Formatter to apply when setting value.
|
|
601
|
+
:return: Return self so this method can easily be chained.
|
|
602
|
+
"""
|
|
603
|
+
return self
|
|
604
|
+
|
|
605
|
+
@property
|
|
606
|
+
def rows(self):
|
|
607
|
+
# type: () -> int
|
|
608
|
+
"""Return the number of rows in the range."""
|
|
609
|
+
raise Exception("Not supported when running outside of Excel")
|
|
610
|
+
|
|
611
|
+
@property
|
|
612
|
+
def columns(self):
|
|
613
|
+
# type: () -> int
|
|
614
|
+
"""Return the number of columns in the range."""
|
|
615
|
+
raise Exception("Not supported when running outside of Excel")
|
|
616
|
+
|
|
617
|
+
def row(self, i):
|
|
618
|
+
# type: (int) -> XLCell
|
|
619
|
+
"""Return a new XLCell for a row of this instance.
|
|
620
|
+
|
|
621
|
+
:param i: Index from 0 for the row to return.
|
|
622
|
+
"""
|
|
623
|
+
raise Exception("Not supported when running outside of Excel")
|
|
624
|
+
|
|
625
|
+
def column(self, i):
|
|
626
|
+
# type: (int) -> XLCell
|
|
627
|
+
"""Return a new XLCell for a column of this instance.
|
|
628
|
+
|
|
629
|
+
:param i: Index from 0 for the column to return.
|
|
630
|
+
"""
|
|
631
|
+
raise Exception("Not supported when running outside of Excel")
|
|
632
|
+
|
|
633
|
+
def cell(self, row, column):
|
|
634
|
+
# type: (int, int) -> XLCell
|
|
635
|
+
"""Return a new XLCell for an individual cell of this instance.
|
|
636
|
+
|
|
637
|
+
:param row: Index from 0 for the row to select.
|
|
638
|
+
:param column: Index from 0 for the column to select.
|
|
639
|
+
"""
|
|
640
|
+
raise Exception("Not supported when running outside of Excel")
|
|
641
|
+
|
|
642
|
+
def offset(self, rows=0, columns=0):
|
|
643
|
+
# type: (int, int) -> XLCell
|
|
644
|
+
"""Return a new XLCell offset from this one by rows and columns.
|
|
645
|
+
|
|
646
|
+
:param rows: Number of rows to offset by.
|
|
647
|
+
:param columns: Number of columns to offset by.
|
|
648
|
+
"""
|
|
649
|
+
raise Exception("Not supported when running outside of Excel")
|
|
650
|
+
|
|
651
|
+
def resize(self, rows=None, columns=None):
|
|
652
|
+
# type: (typing.Union[int, None], typing.Union[int, None]) -> XLCell
|
|
653
|
+
"""Return a new XLCell in the same top left location, resized to rows and columns.
|
|
654
|
+
|
|
655
|
+
:param rows: Number of rows after resizing, or None to keep the same.
|
|
656
|
+
:param columns: Number of columns after resizing, or None to keep the same.
|
|
657
|
+
"""
|
|
658
|
+
raise Exception("Not supported when running outside of Excel")
|
|
659
|
+
|
|
660
|
+
class IRibbonUI:
|
|
661
|
+
"""Wrapper for the Excel IRibbonUI COM interface.
|
|
662
|
+
|
|
663
|
+
The object that is returned by the onLoad procedure specified
|
|
664
|
+
on the customUI tag. The object contains methods for invalidating
|
|
665
|
+
control properties and for refreshing the user interface.
|
|
666
|
+
|
|
667
|
+
The IRibbonUI object does not generate events in its interaction
|
|
668
|
+
with the user. Instead, ribbon elements perform callbacks to your
|
|
669
|
+
code, and the linkage between ribbon elements and your code is
|
|
670
|
+
defined in the XML that describes your ribbon additions.
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
def Invalidate(self):
|
|
674
|
+
raise Exception("Not supported when running outside of Excel")
|
|
675
|
+
|
|
676
|
+
def InvalidateControl(self,
|
|
677
|
+
control_id # type: str
|
|
678
|
+
):
|
|
679
|
+
raise Exception("Not supported when running outside of Excel")
|
|
680
|
+
|
|
681
|
+
def InvalidateControlMso(self,
|
|
682
|
+
control_id # type: str
|
|
683
|
+
):
|
|
684
|
+
raise Exception("Not supported when running outside of Excel")
|
|
685
|
+
|
|
686
|
+
def ActivateTab(self,
|
|
687
|
+
tab_id # type: str
|
|
688
|
+
):
|
|
689
|
+
raise Exception("Not supported when running outside of Excel")
|
|
690
|
+
|
|
691
|
+
def ActivateTabMso(self,
|
|
692
|
+
tab_id # type: str
|
|
693
|
+
):
|
|
694
|
+
raise Exception("Not supported when running outside of Excel")
|
|
695
|
+
|
|
696
|
+
def ActivateTabQ(self,
|
|
697
|
+
tab_id # type: str
|
|
698
|
+
):
|
|
699
|
+
raise Exception("Not supported when running outside of Excel")
|
|
700
|
+
|
|
701
|
+
class IRibbonControl:
|
|
702
|
+
"""Wrapper for the Excel IRibbonControl COM interface.
|
|
703
|
+
|
|
704
|
+
Represents the object passed into the callback procedure of a control
|
|
705
|
+
in a ribbon or another user interface that can be customized by using
|
|
706
|
+
Office Fluent ribbon extensibility.
|
|
707
|
+
"""
|
|
708
|
+
|
|
709
|
+
@property
|
|
710
|
+
def Id(self): # type: (...) -> str
|
|
711
|
+
raise Exception("Not supported when running outside of Excel")
|
|
712
|
+
|
|
713
|
+
@property
|
|
714
|
+
def Tag(self): # type: (...) -> str
|
|
715
|
+
raise Exception("Not supported when running outside of Excel")
|
|
716
|
+
|
|
717
|
+
@property
|
|
718
|
+
def Context(self): # type: (...) -> typing.Any
|
|
719
|
+
raise Exception("Not supported when running outside of Excel")
|
|
720
|
+
|
|
721
|
+
_pd_pandas = None
|
|
722
|
+
_pd_numpy = None
|
|
723
|
+
def _pandas_get_imports():
|
|
724
|
+
"""Convenience function to lazily import pandas and numpy."""
|
|
725
|
+
global _pd_pandas, _pd_numpy
|
|
726
|
+
if _pd_pandas is None:
|
|
727
|
+
import pandas as pandas_module # type: ignore
|
|
728
|
+
_pd_pandas = pandas_module
|
|
729
|
+
if _pd_numpy is None:
|
|
730
|
+
import numpy as numpy_module # type: ignore
|
|
731
|
+
_pd_numpy = numpy_module
|
|
732
|
+
return _pd_pandas, _pd_numpy
|
|
733
|
+
|
|
734
|
+
class ObjectCacheKeyError(KeyError):
|
|
735
|
+
"""Key not found in object cache"""
|
|
736
|
+
pass
|
|
737
|
+
|
|
738
|
+
class SpillError(RuntimeError):
|
|
739
|
+
"""Exception used when an Excel array doesn't have
|
|
740
|
+
room to expand to the size required."""
|
|
741
|
+
pass
|
|
742
|
+
|
|
743
|
+
class CalcError(RuntimeError):
|
|
744
|
+
"""Exception used when setting an async value after the current
|
|
745
|
+
calculation has ended."""
|
|
746
|
+
pass
|
|
747
|
+
|
|
748
|
+
class TableBase:
|
|
749
|
+
"""
|
|
750
|
+
Base class for writing Tables to Excel.
|
|
751
|
+
|
|
752
|
+
This class can be used as a base class for user defined table classes
|
|
753
|
+
to customize how tables get written to Excel.
|
|
754
|
+
|
|
755
|
+
The ``Table`` class is an implementation of this class.
|
|
756
|
+
|
|
757
|
+
When writing a table to Excel, for example::
|
|
758
|
+
|
|
759
|
+
cell = XLCell.from_range(rng)
|
|
760
|
+
cell.value = Table(..)
|
|
761
|
+
|
|
762
|
+
the following happens:
|
|
763
|
+
|
|
764
|
+
1. Table.find_table(rng) is called to see if there is an existing ListObject object.
|
|
765
|
+
2. If no existing ListObject is found, Table.create_table(rng) is called.
|
|
766
|
+
3. If the ListObject size is different from that returned by Table.rows() and
|
|
767
|
+
Table.columns(), Table.resize_table(list_object) is called.
|
|
768
|
+
4. Table.update_table(list_object) is called to update the data in the
|
|
769
|
+
ListObject table object.
|
|
770
|
+
5. Finally, Table.apply_filters and Table.apply_sorting are called to (re)apply
|
|
771
|
+
any filtering and sorting to the table.
|
|
772
|
+
|
|
773
|
+
"""
|
|
774
|
+
|
|
775
|
+
def com_package(self):
|
|
776
|
+
"""Return the ``com_package`` to use when passing COM objects to methods of this class.
|
|
777
|
+
Can be one of `pythoncom`, `win32com`, `comtypes` or `None` to use the default set
|
|
778
|
+
in the pyxll.cfg file.
|
|
779
|
+
"""
|
|
780
|
+
return None
|
|
781
|
+
|
|
782
|
+
def find_table(self, xl_range):
|
|
783
|
+
"""Finds the ListObject for the table.
|
|
784
|
+
This is called when writing a table to a range to find an existing table
|
|
785
|
+
to update, if there is one.
|
|
786
|
+
|
|
787
|
+
:param xl_range: Range where the table is being written to as a Range COM object.
|
|
788
|
+
:return: ListObject COM object or None if not found.
|
|
789
|
+
"""
|
|
790
|
+
raise NotImplementedError()
|
|
791
|
+
|
|
792
|
+
def create_table(self, xl_range):
|
|
793
|
+
"""Creates a new ListObject for the table.
|
|
794
|
+
This is called if ``find_table`` returns None.
|
|
795
|
+
|
|
796
|
+
:param xl_range: Range where the table should be placed as a Range COM object.
|
|
797
|
+
:return: ListObject COM object.
|
|
798
|
+
"""
|
|
799
|
+
raise NotImplementedError()
|
|
800
|
+
|
|
801
|
+
def rows(self):
|
|
802
|
+
"""Return the number of rows in the table, excluding any header row."""
|
|
803
|
+
raise NotImplementedError()
|
|
804
|
+
|
|
805
|
+
def columns(self):
|
|
806
|
+
"""Return the number of columns in the table."""
|
|
807
|
+
raise NotImplementedError()
|
|
808
|
+
|
|
809
|
+
def resize_table(self, xl_list_object, rows, columns):
|
|
810
|
+
"""Resizes the ListObject to match the new data.
|
|
811
|
+
|
|
812
|
+
:param xl_list_object: Existing table as a ListObject COM object.
|
|
813
|
+
:param rows: Number of rows to resize the table to (excluding header row).
|
|
814
|
+
:param columns: Number of columns to resize the table to.
|
|
815
|
+
|
|
816
|
+
:return: ListObject COM object.
|
|
817
|
+
"""
|
|
818
|
+
raise NotImplementedError()
|
|
819
|
+
|
|
820
|
+
def update_table(self, xl_list_object):
|
|
821
|
+
"""Update the ListObject by setting the data on it.
|
|
822
|
+
|
|
823
|
+
:param xl_list_object: Existing table as a ListObject COM object.
|
|
824
|
+
"""
|
|
825
|
+
raise NotImplementedError()
|
|
826
|
+
|
|
827
|
+
def apply_filters(self, xl_list_object):
|
|
828
|
+
"""Apply any filters to the table object.
|
|
829
|
+
|
|
830
|
+
:param xl_list_object: Existing table as a ListObject COM object.
|
|
831
|
+
"""
|
|
832
|
+
raise NotImplementedError()
|
|
833
|
+
|
|
834
|
+
def apply_sorting(self, xl_list_object):
|
|
835
|
+
"""Apply any sorting to the table object.
|
|
836
|
+
|
|
837
|
+
:param xl_list_object: Existing table as a ListObject COM object.
|
|
838
|
+
"""
|
|
839
|
+
raise NotImplementedError()
|
|
840
|
+
|
|
841
|
+
def on_error(self, exc_value, xl_range):
|
|
842
|
+
"""
|
|
843
|
+
Called if an error occurs when creating or updating a table.
|
|
844
|
+
|
|
845
|
+
:param exc_value: The exception object raised.
|
|
846
|
+
:param xl_range: The range that was to be used for the table.
|
|
847
|
+
"""
|
|
848
|
+
raise NotImplementedError()
|
|
849
|
+
|
|
850
|
+
class Table(TableBase):
|
|
851
|
+
|
|
852
|
+
def __init__(self, data, name=None, type=None, **kwargs):
|
|
853
|
+
"""
|
|
854
|
+
:param data: DataFrame or other type that can be converted to ``var[][]``.
|
|
855
|
+
:param name: Table name (optional)
|
|
856
|
+
:param type: Type signature for `data`. If None, data must be a pandas or polars DataFrame or a list of lists.
|
|
857
|
+
:param kwargs: Additional type parameters.
|
|
858
|
+
"""
|
|
859
|
+
TableBase.__init__(self)
|
|
860
|
+
self.__name = name
|
|
861
|
+
self.__data = data
|
|
862
|
+
self.__type = type
|
|
863
|
+
self.__kwargs = kwargs
|
|
864
|
+
|
|
865
|
+
@property
|
|
866
|
+
def name(self):
|
|
867
|
+
"""Name of table.
|
|
868
|
+
Can be fully qualified, eg [Book1]Sheet1!Table1
|
|
869
|
+
or if None a name will get generated.
|
|
870
|
+
"""
|
|
871
|
+
return self.__name
|
|
872
|
+
|
|
873
|
+
@name.setter
|
|
874
|
+
def name(self, name):
|
|
875
|
+
self.__name = name
|
|
876
|
+
|
|
877
|
+
@property
|
|
878
|
+
def data(self):
|
|
879
|
+
"""Data object that was passed to the constructor.
|
|
880
|
+
"""
|
|
881
|
+
return self.__data
|
|
882
|
+
|
|
883
|
+
@property
|
|
884
|
+
def type(self):
|
|
885
|
+
"""Data type that was passed to the constructor, including
|
|
886
|
+
type parameters passed as kwargs.
|
|
887
|
+
|
|
888
|
+
The return type should be considered opaque but can be used with
|
|
889
|
+
pyxll.get_type_converter.
|
|
890
|
+
"""
|
|
891
|
+
if self.__kwargs:
|
|
892
|
+
raise NotImplementedError()
|
|
893
|
+
return self.__type
|
|
894
|
+
|
|
895
|
+
def write(self, target):
|
|
896
|
+
"""
|
|
897
|
+
Find or create a table from the target cell and update it.
|
|
898
|
+
|
|
899
|
+
:param target: XLCell or Range instance to write the table to.
|
|
900
|
+
:return: ListObject
|
|
901
|
+
"""
|
|
902
|
+
# Implemented in PyXLL add-in
|
|
903
|
+
raise NotImplementedError()
|
|
904
|
+
|
|
905
|
+
#
|
|
906
|
+
# API functions / decorators
|
|
907
|
+
#
|
|
908
|
+
|
|
909
|
+
def get_config():
|
|
910
|
+
# type: () -> configparser.ConfigParser
|
|
911
|
+
"""returns the PyXLL config as a ConfigParser.RawConfigParser instance"""
|
|
912
|
+
raise Exception("Not supported when running outside of Excel")
|
|
913
|
+
|
|
914
|
+
def xl_version():
|
|
915
|
+
# type: () -> float
|
|
916
|
+
"""
|
|
917
|
+
returns the version of Excel the addin is running in as a float.
|
|
918
|
+
|
|
919
|
+
8.0 => Excel 97
|
|
920
|
+
9.0 => Excel 2000
|
|
921
|
+
10.0 => Excel 2002
|
|
922
|
+
11.0 => Excel 2003
|
|
923
|
+
12.0 => Excel 2007
|
|
924
|
+
14.0 => Excel 2010
|
|
925
|
+
"""
|
|
926
|
+
raise Exception("Not supported when running outside of Excel")
|
|
927
|
+
|
|
928
|
+
def xl_func(signature=None, # type: typing.Union[str, _Function, None]
|
|
929
|
+
category=None, # type: typing.Union[str, None]
|
|
930
|
+
help_topic="", # type: str
|
|
931
|
+
thread_safe=False, # type: bool
|
|
932
|
+
macro=False, # type: bool
|
|
933
|
+
allow_abort=None, # type: typing.Union[bool, None]
|
|
934
|
+
volatile=None, # type: typing.Union[bool, None]
|
|
935
|
+
disable_function_wizard_calc=None, # type: typing.Union[bool, None]
|
|
936
|
+
disable_replace_calc=None, # type: typing.Union[bool, None]
|
|
937
|
+
arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
|
|
938
|
+
name=None, # type: typing.Union[str, None]
|
|
939
|
+
auto_resize=None, # type: typing.Union[bool, None]
|
|
940
|
+
hidden=False, # type: bool
|
|
941
|
+
transpose=False, # type: bool
|
|
942
|
+
recalc_on_open=None, # type: typing.Union[bool, None]
|
|
943
|
+
formatter=None, # type: typing.Union[BaseFormatter, None]
|
|
944
|
+
async_cache=None, # type: typing.Union[bool, None]
|
|
945
|
+
nan_value=_no_value,
|
|
946
|
+
posinf_value=_no_value,
|
|
947
|
+
neginf_value=_no_value,
|
|
948
|
+
none_value=_no_value
|
|
949
|
+
): # type: (...) -> _Decorator
|
|
950
|
+
"""
|
|
951
|
+
Decorator for exposing functions to excel, e.g.:
|
|
952
|
+
|
|
953
|
+
@xl_func
|
|
954
|
+
def my_xl_function(a, b, c):
|
|
955
|
+
'''docstrings appear as helptext in excel'''
|
|
956
|
+
return "%s %s %s" % (a, b, c)
|
|
957
|
+
|
|
958
|
+
A signature may be provided to give type information for the
|
|
959
|
+
arguments and return type, e.g.:
|
|
960
|
+
|
|
961
|
+
@xl_func("string a, int b, float c: string")
|
|
962
|
+
def my_xl_function(a, b, c)
|
|
963
|
+
return "%s %d %f" % (a, b, c)
|
|
964
|
+
|
|
965
|
+
Valid types are:
|
|
966
|
+
str, string, int, bool, float, float[], var or types registered
|
|
967
|
+
with xl_arg_type.
|
|
968
|
+
|
|
969
|
+
The return type is optional, it will default to var.
|
|
970
|
+
|
|
971
|
+
Or where available, type hints may be used:
|
|
972
|
+
|
|
973
|
+
@xl_func
|
|
974
|
+
def strlen(x: str) -> int:
|
|
975
|
+
return len(x)
|
|
976
|
+
|
|
977
|
+
"""
|
|
978
|
+
# xl_func may be called with no arguments as a plain decorator, in which
|
|
979
|
+
# case the first argument will be the function it's applied to.
|
|
980
|
+
if signature is not None and callable(signature):
|
|
981
|
+
return signature
|
|
982
|
+
|
|
983
|
+
# or it will eturn a dectorator.
|
|
984
|
+
def dummy_decorator(func):
|
|
985
|
+
return func
|
|
986
|
+
return dummy_decorator
|
|
987
|
+
|
|
988
|
+
def xl_arg_doc(arg_name, # type: str
|
|
989
|
+
docstring # type: str
|
|
990
|
+
): # type: (...) -> _Decorator
|
|
991
|
+
"""
|
|
992
|
+
Decorator for documenting a function's named parameters.
|
|
993
|
+
Must be applied before xl_func.
|
|
994
|
+
|
|
995
|
+
eg:
|
|
996
|
+
|
|
997
|
+
@xl_func("int a, int b: int")
|
|
998
|
+
@xl_arg_doc("a", "this is the docstring for a")
|
|
999
|
+
@xl_arg_doc("b", "this is the docstring for b")
|
|
1000
|
+
def my_xl_function(a, b):
|
|
1001
|
+
return a + b
|
|
1002
|
+
|
|
1003
|
+
Alternatively if no docstrings are explicitly supplied
|
|
1004
|
+
and the function has a docstring, PyXLL will try and
|
|
1005
|
+
find parameter documentation in the docstring.
|
|
1006
|
+
|
|
1007
|
+
@xl_func("int a, int b: int")
|
|
1008
|
+
def my_xl_function(a, b):
|
|
1009
|
+
'''
|
|
1010
|
+
return a + b
|
|
1011
|
+
|
|
1012
|
+
a : this is the docstring for a
|
|
1013
|
+
b : this is the docstring for b
|
|
1014
|
+
'''
|
|
1015
|
+
return a + b
|
|
1016
|
+
|
|
1017
|
+
"""
|
|
1018
|
+
def dummy_decorator(func):
|
|
1019
|
+
return func
|
|
1020
|
+
return dummy_decorator
|
|
1021
|
+
|
|
1022
|
+
def xl_macro(signature=None, # type: typing.Union[str, _Function, None]
|
|
1023
|
+
allow_abort=None, # type: typing.Union[bool, None]
|
|
1024
|
+
arg_descriptions=None, # type: typing.Union[typing.Dict[str, str], None]
|
|
1025
|
+
name=None, # type: typing.Union[str, None]
|
|
1026
|
+
shortcut=None, # type: typing.Union[str, None]
|
|
1027
|
+
transpose=False, # type: typing.Union[bool, None]
|
|
1028
|
+
nan_value=_no_value,
|
|
1029
|
+
posinf_value=_no_value,
|
|
1030
|
+
neginf_value=_no_value,
|
|
1031
|
+
none_value=_no_value,
|
|
1032
|
+
disable_calculation=False, # type: bool
|
|
1033
|
+
disable_screen_updating=False, # type: bool
|
|
1034
|
+
disable_alerts=False, # type: bool
|
|
1035
|
+
restore_selection=False, # type: bool
|
|
1036
|
+
restore_active_sheet=False # type: bool
|
|
1037
|
+
): # type: (...) -> _Decorator
|
|
1038
|
+
"""
|
|
1039
|
+
Decorator for exposing python functions as macros.
|
|
1040
|
+
|
|
1041
|
+
Macros are used like VBA macros and can be assigned to buttons.
|
|
1042
|
+
They take no arguments the return value is not used.
|
|
1043
|
+
|
|
1044
|
+
Macros may call macro sheet functions and may call back
|
|
1045
|
+
into Excel like menu items.
|
|
1046
|
+
|
|
1047
|
+
eg:
|
|
1048
|
+
@xl_macro
|
|
1049
|
+
def my_macro():
|
|
1050
|
+
win32api.MessageBox(0, "my_macro", "my_macro")
|
|
1051
|
+
|
|
1052
|
+
A signature may be applied to the function, e.g.:
|
|
1053
|
+
|
|
1054
|
+
@xl_macro("string x: int")
|
|
1055
|
+
def strlen(x):
|
|
1056
|
+
return len(x)
|
|
1057
|
+
|
|
1058
|
+
Or where possible, type hints may be used:
|
|
1059
|
+
|
|
1060
|
+
@xl_macro
|
|
1061
|
+
def strlen(x: str) -> int:
|
|
1062
|
+
return len(x)
|
|
1063
|
+
|
|
1064
|
+
"""
|
|
1065
|
+
# xl_macro may be called with no arguments as a plain decorator, in which
|
|
1066
|
+
# case the first argument will be the function it's applied to.
|
|
1067
|
+
if signature is not None and callable(signature):
|
|
1068
|
+
return signature
|
|
1069
|
+
|
|
1070
|
+
# or it will eturn a dectorator.
|
|
1071
|
+
def dummy_decorator(func):
|
|
1072
|
+
return func
|
|
1073
|
+
return dummy_decorator
|
|
1074
|
+
|
|
1075
|
+
def xl_menu(name, # type: str
|
|
1076
|
+
menu=None, # type: typing.Union[str, None]
|
|
1077
|
+
sub_menu=None, # type: typing.Union[str, None]
|
|
1078
|
+
order=None, # type: typing.Union[int, None]
|
|
1079
|
+
sub_order=None, # type: typing.Union[int, None]
|
|
1080
|
+
menu_order=None, # type: typing.Union[int, None]
|
|
1081
|
+
allow_abort=None, # type: typing.Union[bool, None]
|
|
1082
|
+
shortcut=None # type: typing.Union[str, None]
|
|
1083
|
+
): # type: (...) -> _Decorator
|
|
1084
|
+
"""
|
|
1085
|
+
Decorator for creating custom menu items.
|
|
1086
|
+
|
|
1087
|
+
eg.
|
|
1088
|
+
|
|
1089
|
+
@xl_menu("My menu item")
|
|
1090
|
+
def my_menu_item():
|
|
1091
|
+
print "my menu item was called"
|
|
1092
|
+
|
|
1093
|
+
Adds a menu item 'My menu item' to the default menu (PyXLL or addin
|
|
1094
|
+
name).
|
|
1095
|
+
|
|
1096
|
+
@xl_menu("My menu item", menu="My Menu")
|
|
1097
|
+
def my_menu_item():
|
|
1098
|
+
print "my menu item was called"
|
|
1099
|
+
|
|
1100
|
+
Creates a new menu "My Menu" and adds "My menu item" to it.
|
|
1101
|
+
|
|
1102
|
+
@xl_menu("Mysub-menu item", menu="My Menu", sub_menu="My Sub Menu")
|
|
1103
|
+
def my_menu_item():
|
|
1104
|
+
print "my menu item was called"
|
|
1105
|
+
|
|
1106
|
+
Creates a new sub-menu "My Sub Menu" and adds "My sub-menu item"
|
|
1107
|
+
to it.
|
|
1108
|
+
If the menu My Menu didn't already exist, it would create it too.
|
|
1109
|
+
"""
|
|
1110
|
+
def dummy_decorator(func):
|
|
1111
|
+
return func
|
|
1112
|
+
return dummy_decorator
|
|
1113
|
+
|
|
1114
|
+
def xl_license_notifier(func):
|
|
1115
|
+
# type: (_Function) -> _Function
|
|
1116
|
+
"""
|
|
1117
|
+
Decorator for callbacks to notify user code of the current state of
|
|
1118
|
+
the license.
|
|
1119
|
+
|
|
1120
|
+
The decorated function must be of the form:
|
|
1121
|
+
def callback(string name, datetime.date expdate, int days_left)
|
|
1122
|
+
|
|
1123
|
+
All registered callbacks are called when the license is checked at the time
|
|
1124
|
+
pyxll is first loaded, and again each time the license is checked and there
|
|
1125
|
+
has been a change since the last time it was checked.
|
|
1126
|
+
"""
|
|
1127
|
+
return func
|
|
1128
|
+
|
|
1129
|
+
def xl_on_close(func):
|
|
1130
|
+
# type: (_Function) -> _Function
|
|
1131
|
+
"""
|
|
1132
|
+
Decorator for callbacks that should be called when Excel is about
|
|
1133
|
+
to be closed.
|
|
1134
|
+
|
|
1135
|
+
Even after this function has been called, it's possible Excel won't
|
|
1136
|
+
actually close as the user may veto it.
|
|
1137
|
+
|
|
1138
|
+
The function should take no arguments.
|
|
1139
|
+
"""
|
|
1140
|
+
return func
|
|
1141
|
+
|
|
1142
|
+
def xl_on_reload(func):
|
|
1143
|
+
# type: (_Function) -> _Function
|
|
1144
|
+
"""
|
|
1145
|
+
Decorator for callbacks that should be called after a reload is
|
|
1146
|
+
attempted.
|
|
1147
|
+
|
|
1148
|
+
The callback takes a list of tuples of three three items:
|
|
1149
|
+
(modulename, module, exc_info)
|
|
1150
|
+
|
|
1151
|
+
When a module has been loaded successfully, exc_info is None.
|
|
1152
|
+
When a module has failed to load, module is None and exc_info
|
|
1153
|
+
is the exception information (exc_type, exc_value, exc_traceback).
|
|
1154
|
+
"""
|
|
1155
|
+
return func
|
|
1156
|
+
|
|
1157
|
+
def xl_on_open(func):
|
|
1158
|
+
# type: (_Function) -> _Function
|
|
1159
|
+
"""
|
|
1160
|
+
Decorator for callbacks that should be called after PyXLL has
|
|
1161
|
+
been opened and the user modules have been imported.
|
|
1162
|
+
|
|
1163
|
+
The callback takes a list of tuples of three three items:
|
|
1164
|
+
(modulename, module, exc_info)
|
|
1165
|
+
|
|
1166
|
+
When a module has been loaded successfully, exc_info is None.
|
|
1167
|
+
When a module has failed to load, module is None and exc_info
|
|
1168
|
+
is the exception information (exc_type, exc_value, exc_traceback).
|
|
1169
|
+
"""
|
|
1170
|
+
return func
|
|
1171
|
+
|
|
1172
|
+
_async_call_warning_enabled = True
|
|
1173
|
+
def async_call(func, *args, **kwargs):
|
|
1174
|
+
"""
|
|
1175
|
+
Schedule a function to be called after the current Excel
|
|
1176
|
+
calculation cycle has completed.
|
|
1177
|
+
|
|
1178
|
+
The function is called in an Excel macro context with automatic
|
|
1179
|
+
calculation disabled, so it is safe to use :py:func:`xl_app` and
|
|
1180
|
+
other COM and macro functions.
|
|
1181
|
+
|
|
1182
|
+
This can be used by worksheet functions that need to modify the worksheet
|
|
1183
|
+
where calling back into Excel would fail or cause a deadlock.
|
|
1184
|
+
|
|
1185
|
+
NOTE: In the stubs version (not embedded in PyXLL) the function
|
|
1186
|
+
is called immediately.
|
|
1187
|
+
|
|
1188
|
+
:param func: Function or callable object to call in an Excel macro context
|
|
1189
|
+
at some time in the near future.
|
|
1190
|
+
"""
|
|
1191
|
+
global _async_call_warning_enabled
|
|
1192
|
+
if _async_call_warning_enabled:
|
|
1193
|
+
_log.warning("pyxll.async_call is deprecated and will be removed in a future release. "
|
|
1194
|
+
"Use pyxll.schedule_call instead.")
|
|
1195
|
+
_async_call_warning_enabled = False
|
|
1196
|
+
func(*args, **kwargs)
|
|
1197
|
+
|
|
1198
|
+
def schedule_call(func, # type: _Function
|
|
1199
|
+
*args,
|
|
1200
|
+
delay=0, # type: int
|
|
1201
|
+
nowait=False, # type: bool
|
|
1202
|
+
retries=0, # type: int
|
|
1203
|
+
retry_delay=0.0, # type: float
|
|
1204
|
+
retry_backoff=1.0, # type: float
|
|
1205
|
+
retry_filter=None, # type: typing.Union[typing.Callable[[BaseException], bool], None]
|
|
1206
|
+
disable_calculation=False, # type: bool
|
|
1207
|
+
disable_screen_updating=False, # type: bool
|
|
1208
|
+
disable_alerts=False, # type: bool
|
|
1209
|
+
restore_selection=False, # type: bool
|
|
1210
|
+
restore_active_sheet=False # type: bool
|
|
1211
|
+
): # type: (...) -> typing.Union[asyncio.futures.Future[Any], None]
|
|
1212
|
+
"""
|
|
1213
|
+
Schedule a function to be called after the current Excel
|
|
1214
|
+
calculation cycle has completed.
|
|
1215
|
+
|
|
1216
|
+
The function is called in an Excel macro context with automatic
|
|
1217
|
+
calculation disabled, so it is safe to use :py:func:`xl_app` and
|
|
1218
|
+
other COM and macro functions.
|
|
1219
|
+
|
|
1220
|
+
This can be used by worksheet functions that need to modify the worksheet
|
|
1221
|
+
where calling back into Excel would fail or cause a deadlock.
|
|
1222
|
+
|
|
1223
|
+
From Python 3.7 onwards when called from the PyXLL asyncio event loop and
|
|
1224
|
+
'nowait' is not set this function returns an asyncio.Future. This future
|
|
1225
|
+
can be awaited on to get the result of the call.
|
|
1226
|
+
|
|
1227
|
+
NOTE: In the stubs version (not embedded in PyXLL) the function
|
|
1228
|
+
is called immediately.
|
|
1229
|
+
|
|
1230
|
+
:param func: Function or callable object to call in an Excel macro context
|
|
1231
|
+
at some time in the near future.
|
|
1232
|
+
|
|
1233
|
+
:param *args: Arguments to be passed to the the function.
|
|
1234
|
+
|
|
1235
|
+
:param delay: Delay in seconds to wait before calling the function.
|
|
1236
|
+
|
|
1237
|
+
:param nowait: Do not return a Future even if called from the asyncio event loop.
|
|
1238
|
+
|
|
1239
|
+
:param retries: Integer number of times to retry.
|
|
1240
|
+
|
|
1241
|
+
:param retry_delay: Time in seconds to wait between retries.
|
|
1242
|
+
|
|
1243
|
+
:param retry_backoff: Multiplier to apply to 'retry_delay' after each retry. This
|
|
1244
|
+
can be used to increase the time between each retry by setting
|
|
1245
|
+
'retry_backoff' to > 1.0.
|
|
1246
|
+
|
|
1247
|
+
:param retry_filter: Callable that received the exception value in the case of an
|
|
1248
|
+
error. It should return True if a retry should be attempted
|
|
1249
|
+
or False otherwise.
|
|
1250
|
+
|
|
1251
|
+
:param disable_calculation: Disable automatic calculations while the callback is being called.
|
|
1252
|
+
This switches the Excel calculation mode to manual and restores it
|
|
1253
|
+
to its previous mode after the call is complete.
|
|
1254
|
+
|
|
1255
|
+
:param disable_screen_updating: Disable Excel's screen updating while the callback is being called.
|
|
1256
|
+
Screen updating is restored to its previous mode after the call is
|
|
1257
|
+
complete.
|
|
1258
|
+
|
|
1259
|
+
.. warning::
|
|
1260
|
+
|
|
1261
|
+
This function doesn't allow passing keyword arguments to the schedule function.
|
|
1262
|
+
To do that, use functools.partial().::
|
|
1263
|
+
|
|
1264
|
+
# Will schedule "print("Hello", flush=True)"
|
|
1265
|
+
schedule_call(functools.partial(print, "Hello", flush=True))
|
|
1266
|
+
"""
|
|
1267
|
+
|
|
1268
|
+
# In the stubs package the function gets called immediately, regardless
|
|
1269
|
+
# of the delay passed in or what thread we might be running in.
|
|
1270
|
+
result = func(*args)
|
|
1271
|
+
|
|
1272
|
+
if not nowait:
|
|
1273
|
+
# Check to see if we are running in an asyncio event loop
|
|
1274
|
+
try:
|
|
1275
|
+
import asyncio
|
|
1276
|
+
loop = asyncio.get_running_loop()
|
|
1277
|
+
except (ImportError, AttributeError, RuntimeError):
|
|
1278
|
+
return None
|
|
1279
|
+
|
|
1280
|
+
# We are so return the result in a Future
|
|
1281
|
+
future = loop.create_future()
|
|
1282
|
+
future.set_result(result)
|
|
1283
|
+
return future
|
|
1284
|
+
|
|
1285
|
+
return None
|
|
1286
|
+
|
|
1287
|
+
# Ribbon
|
|
1288
|
+
_default_ribbon_xml = """<?xml version="1.0" ?>
|
|
1289
|
+
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" loadImage="pyxll.load_image">
|
|
1290
|
+
<ribbon><tabs/></ribbon>
|
|
1291
|
+
</customUI>
|
|
1292
|
+
"""
|
|
1293
|
+
|
|
1294
|
+
def _xml_to_dom(xml):
|
|
1295
|
+
# type: (Union[minidom.Document, str]) -> minidom.Document
|
|
1296
|
+
"""Takes xml as a string or dom and returns a document object"""
|
|
1297
|
+
if not isinstance(xml, minidom.Document):
|
|
1298
|
+
return minidom.parseString(xml)
|
|
1299
|
+
return xml
|
|
1300
|
+
|
|
1301
|
+
def _validate_ribbon_xml(xml):
|
|
1302
|
+
"""Tests the ribbon xml to make sure it looks reasonable.
|
|
1303
|
+
Returns validated xml as text.
|
|
1304
|
+
"""
|
|
1305
|
+
|
|
1306
|
+
xml = _xml_to_dom(xml)
|
|
1307
|
+
|
|
1308
|
+
if not xml.documentElement:
|
|
1309
|
+
raise AssertionError("Ribbon XML is missing a root document element")
|
|
1310
|
+
|
|
1311
|
+
if not xml.documentElement.tagName == "customUI":
|
|
1312
|
+
raise AssertionError("Ribbon XML document element is expected to be 'customUI' "
|
|
1313
|
+
"(not '%s'" % xml.documentElement.tagName)
|
|
1314
|
+
|
|
1315
|
+
def _assert_unique_attr(element, attr, error, values={}):
|
|
1316
|
+
elements = [element]
|
|
1317
|
+
while elements:
|
|
1318
|
+
element = elements[0]
|
|
1319
|
+
elements = elements[1:] + list(element.childNodes or [])
|
|
1320
|
+
attributes = element.attributes or {}
|
|
1321
|
+
value = getattr(attributes.get(attr, None), "value", None)
|
|
1322
|
+
if value:
|
|
1323
|
+
if value in values:
|
|
1324
|
+
raise AssertionError(error % {"attr": attr, "value": value})
|
|
1325
|
+
values[value] = None
|
|
1326
|
+
|
|
1327
|
+
_assert_unique_attr(xml.documentElement,
|
|
1328
|
+
"id",
|
|
1329
|
+
"Duplicate %(attr)s attribute '%(value)s' found.")
|
|
1330
|
+
|
|
1331
|
+
def _assert_at_most_one(element, tag_name, error):
|
|
1332
|
+
children = {}
|
|
1333
|
+
for child in element.childNodes:
|
|
1334
|
+
if child.nodeType != child.ELEMENT_NODE:
|
|
1335
|
+
continue
|
|
1336
|
+
children.setdefault(child.tagName, [])
|
|
1337
|
+
children[child.tagName].append(child)
|
|
1338
|
+
tag_children = children.get(tag_name, [])
|
|
1339
|
+
if len(tag_children) > 1:
|
|
1340
|
+
raise AssertionError(error)
|
|
1341
|
+
if tag_children:
|
|
1342
|
+
return tag_children[0]
|
|
1343
|
+
|
|
1344
|
+
ribbon = _assert_at_most_one(xml.documentElement,
|
|
1345
|
+
"ribbon",
|
|
1346
|
+
"'customUI' element in ribbon XML should have a single ribbon node")
|
|
1347
|
+
|
|
1348
|
+
if ribbon:
|
|
1349
|
+
_assert_at_most_one(ribbon,
|
|
1350
|
+
"tabs",
|
|
1351
|
+
"'ribbon' element in ribbon XML should have a single tabs node)")
|
|
1352
|
+
|
|
1353
|
+
def set_ribbon_tab(xml, tab_id=None, reload=True):
|
|
1354
|
+
# type: (Union[str, minidom.Document], Union[str, None], bool) -> None
|
|
1355
|
+
"""
|
|
1356
|
+
Sets a tab in the ribbon using an xml fragment.
|
|
1357
|
+
|
|
1358
|
+
:param xml: Ribbon xml as a string containing at least one tab element.
|
|
1359
|
+
:param tab_id: Id of tab to add if multiple tabs exist in the xml.
|
|
1360
|
+
:param reload: If true the ribbon will be refreshed immediately.
|
|
1361
|
+
"""
|
|
1362
|
+
xml = _xml_to_dom(xml)
|
|
1363
|
+
|
|
1364
|
+
if tab_id:
|
|
1365
|
+
tab_id = str(tab_id)
|
|
1366
|
+
for new_tab in xml.getElementsByTagName("tab"):
|
|
1367
|
+
if str(new_tab.getAttribute("id")) == tab_id:
|
|
1368
|
+
break
|
|
1369
|
+
else:
|
|
1370
|
+
raise KeyError("Tab '%s' not found" % tab_id)
|
|
1371
|
+
else:
|
|
1372
|
+
new_tabs = xml.getElementsByTagName("tab")
|
|
1373
|
+
if not new_tabs:
|
|
1374
|
+
raise RuntimeError("No 'tab' elements found")
|
|
1375
|
+
new_tab = new_tabs[0]
|
|
1376
|
+
tab_id = str(new_tab.getAttribute("id") or "")
|
|
1377
|
+
|
|
1378
|
+
new_xml = get_ribbon_xml(join_merged_attrs=False) # type: Union[minidom.Document, str]
|
|
1379
|
+
if not new_xml:
|
|
1380
|
+
new_xml = _default_ribbon_xml
|
|
1381
|
+
new_xml = _xml_to_dom(new_xml)
|
|
1382
|
+
|
|
1383
|
+
tabs = new_xml.getElementsByTagName("tabs")
|
|
1384
|
+
if tabs:
|
|
1385
|
+
tabs = tabs[0] # type: ignore
|
|
1386
|
+
else:
|
|
1387
|
+
ribbon = new_xml.getElementsByTagName("ribbon")
|
|
1388
|
+
if ribbon:
|
|
1389
|
+
ribbon = ribbon[0] # type: ignore
|
|
1390
|
+
else:
|
|
1391
|
+
ribbon = new_xml.createElement("ribbon") # type: ignore
|
|
1392
|
+
new_xml.documentElement.appendChild(ribbon)
|
|
1393
|
+
tabs = new_xml.createElement("tabs") # type: ignore
|
|
1394
|
+
ribbon.appendChild(tabs) # type: ignore
|
|
1395
|
+
|
|
1396
|
+
if tab_id:
|
|
1397
|
+
for tab in tabs.childNodes: # type: ignore
|
|
1398
|
+
if tab.nodeType == tab.ELEMENT_NODE \
|
|
1399
|
+
and str(tab.tagName) == "tab" \
|
|
1400
|
+
and str(tab.getAttribute("id")) == tab_id:
|
|
1401
|
+
tabs.replaceChild(new_tab, tab) # type: ignore
|
|
1402
|
+
break
|
|
1403
|
+
else:
|
|
1404
|
+
tabs.appendChild(new_tab) # type: ignore
|
|
1405
|
+
else:
|
|
1406
|
+
tabs.appendChild(new_tab) # type: ignore
|
|
1407
|
+
|
|
1408
|
+
set_ribbon_xml(new_xml, reload=reload, keep_merged_attrs=True)
|
|
1409
|
+
|
|
1410
|
+
def remove_ribbon_tab(tab_id, reload=True):
|
|
1411
|
+
# type: (str, bool) -> bool
|
|
1412
|
+
"""
|
|
1413
|
+
Removes a tab previously added to the ribbon.
|
|
1414
|
+
|
|
1415
|
+
:param tab_id: Id of tab to remove
|
|
1416
|
+
:param reload: If true the ribbon will be refreshed immediately.
|
|
1417
|
+
:return: True if a tab was removed, False otherwise.
|
|
1418
|
+
"""
|
|
1419
|
+
new_xml = get_ribbon_xml(join_merged_attrs=False)
|
|
1420
|
+
if not new_xml:
|
|
1421
|
+
return False
|
|
1422
|
+
|
|
1423
|
+
new_xml = minidom.parseString(new_xml) # type: ignore
|
|
1424
|
+
tabs = new_xml.getElementsByTagName("tab") # type: ignore
|
|
1425
|
+
if not tabs:
|
|
1426
|
+
return False
|
|
1427
|
+
|
|
1428
|
+
updated = False
|
|
1429
|
+
tab_id = str(tab_id)
|
|
1430
|
+
for tab in tabs:
|
|
1431
|
+
if str(tab.getAttribute("id")) == tab_id:
|
|
1432
|
+
tab.parentNode.removeChild(tab)
|
|
1433
|
+
updated = True
|
|
1434
|
+
|
|
1435
|
+
if not updated:
|
|
1436
|
+
return False
|
|
1437
|
+
|
|
1438
|
+
set_ribbon_xml(new_xml, reload=reload, keep_merged_attrs=True)
|
|
1439
|
+
return updated
|
|
1440
|
+
|
|
1441
|
+
_ribbon_xml = ""
|
|
1442
|
+
|
|
1443
|
+
def load_image(filename):
|
|
1444
|
+
# type: (str) -> _COMObject
|
|
1445
|
+
"""
|
|
1446
|
+
Loads an image file and returns it as a COM IPicture object suitable for use when
|
|
1447
|
+
customizing the ribbon.
|
|
1448
|
+
|
|
1449
|
+
This function can be set at the Ribbon image handler by setting the loadImage attribute on
|
|
1450
|
+
the customUI element in the ribbon XML file.
|
|
1451
|
+
|
|
1452
|
+
.. code-block:: xml
|
|
1453
|
+
:emphasize-lines: 2, 11
|
|
1454
|
+
|
|
1455
|
+
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui"
|
|
1456
|
+
loadImage="pyxll.load_image">
|
|
1457
|
+
<ribbon>
|
|
1458
|
+
<tabs>
|
|
1459
|
+
<tab id="CustomTab" label="Custom Tab">
|
|
1460
|
+
<group id="Tools" label="Tools">
|
|
1461
|
+
<button id="Reload"
|
|
1462
|
+
size="large"
|
|
1463
|
+
label="Reload PyXLL"
|
|
1464
|
+
onAction="pyxll.reload"
|
|
1465
|
+
image="reload.png"/>
|
|
1466
|
+
</group>
|
|
1467
|
+
</tab>
|
|
1468
|
+
</tabs>
|
|
1469
|
+
</ribbon>
|
|
1470
|
+
</customUI>
|
|
1471
|
+
|
|
1472
|
+
Or it can be used when returning an image from a getImage callback.
|
|
1473
|
+
|
|
1474
|
+
:param string filename: Filename of the image file to load. This may be an absolute path or relative to
|
|
1475
|
+
the ribbon XML file.
|
|
1476
|
+
|
|
1477
|
+
:return: A COM IPicture object (the exact type depends
|
|
1478
|
+
on the com_package setting in the config file.
|
|
1479
|
+
"""
|
|
1480
|
+
raise Exception("Not supported when running outside of Excel")
|
|
1481
|
+
|
|
1482
|
+
def get_ribbon_xml(join_merged_attrs=True):
|
|
1483
|
+
# type: (bool) -> str
|
|
1484
|
+
"""Returns the ribbon XML currenly in use by PyXLL."""
|
|
1485
|
+
return _ribbon_xml
|
|
1486
|
+
|
|
1487
|
+
def set_ribbon_xml(xml, reload=True, keep_merged_attrs=False):
|
|
1488
|
+
# type: (typing.Union[str, minidom.Document], bool, bool) -> None
|
|
1489
|
+
"""
|
|
1490
|
+
Sets the XML used by PyXLL for customizing the ribbon.
|
|
1491
|
+
|
|
1492
|
+
:param xml: XML document to set as the current ribbon
|
|
1493
|
+
:param reload: If true the ribbon will be refreshed immediately.
|
|
1494
|
+
"""
|
|
1495
|
+
|
|
1496
|
+
_validate_ribbon_xml(xml)
|
|
1497
|
+
|
|
1498
|
+
if _have_minidom:
|
|
1499
|
+
if isinstance(xml, minidom.Document):
|
|
1500
|
+
xml = xml.toxml()
|
|
1501
|
+
|
|
1502
|
+
global _ribbon_xml
|
|
1503
|
+
_ribbon_xml = xml # type: ignore
|
|
1504
|
+
|
|
1505
|
+
def get_ribbon_ui():
|
|
1506
|
+
# type: () -> _COMObject
|
|
1507
|
+
"""Returns the Ribbon COM object.
|
|
1508
|
+
"""
|
|
1509
|
+
raise Exception("Not supported when running outside of Excel")
|
|
1510
|
+
|
|
1511
|
+
class ErrorContext:
|
|
1512
|
+
"""Context object passed to the PyXLL error handler."""
|
|
1513
|
+
|
|
1514
|
+
class Type:
|
|
1515
|
+
"""Type to indicate the origination of the error."""
|
|
1516
|
+
UDF = "udf"
|
|
1517
|
+
MACRO = "macro"
|
|
1518
|
+
MENU = "menu"
|
|
1519
|
+
RIBBON = "ribbon"
|
|
1520
|
+
IMPORT = "import"
|
|
1521
|
+
|
|
1522
|
+
def __init__(self, error_type, function_name=None, import_errors=None):
|
|
1523
|
+
self.error_type = error_type
|
|
1524
|
+
self.function_name = function_name
|
|
1525
|
+
self.import_errors = import_errors
|
|
1526
|
+
|
|
1527
|
+
def error_handler(context, exc_type, exc_value, exc_traceback):
|
|
1528
|
+
"""Standard PyXLL error handler."""
|
|
1529
|
+
# For UDFs return a preview of the error as a single line
|
|
1530
|
+
if context.error_type in (ErrorContext.Type.UDF, ErrorContext.Type.MACRO):
|
|
1531
|
+
error = "##" + getattr(exc_type, "__name__", "Error")
|
|
1532
|
+
msg = str(exc_value)
|
|
1533
|
+
|
|
1534
|
+
# Don't keep nesting errors if they're the same (eg ##ObjectCacheKeyError...)
|
|
1535
|
+
unquoted_msg = msg.strip()
|
|
1536
|
+
while len(unquoted_msg) > 1 and unquoted_msg[0] == unquoted_msg[-1] and unquoted_msg[0] in "\"'":
|
|
1537
|
+
unquoted_msg = unquoted_msg[1:-1]
|
|
1538
|
+
if unquoted_msg.startswith(error):
|
|
1539
|
+
return unquoted_msg
|
|
1540
|
+
|
|
1541
|
+
if msg:
|
|
1542
|
+
error += ": " + msg
|
|
1543
|
+
|
|
1544
|
+
# Truncate long errors to avoid conversion problems
|
|
1545
|
+
if len(error) > 254:
|
|
1546
|
+
return error[:251] + "..."
|
|
1547
|
+
|
|
1548
|
+
return error
|
|
1549
|
+
|
|
1550
|
+
# For menus and ribbon functions display an error message.
|
|
1551
|
+
if context.error_type in (ErrorContext.Type.MENU, ErrorContext.Type.RIBBON):
|
|
1552
|
+
message = ""
|
|
1553
|
+
if context.function_name:
|
|
1554
|
+
message = "Error calling '%s'\n\n" % context.function_name
|
|
1555
|
+
elif context.error_type == ErrorContext.Type.RIBBON:
|
|
1556
|
+
message = "PyXLL Ribbon Error\n\n"
|
|
1557
|
+
exc_type_name = getattr(exc_type, "__name__", "Exception")
|
|
1558
|
+
message += str(exc_type_name) + (str(exc_value) and (": " + str(exc_value)) or "") + "\n\n"
|
|
1559
|
+
|
|
1560
|
+
exc_instance = exc_value
|
|
1561
|
+
if not isinstance(exc_instance, BaseException):
|
|
1562
|
+
try:
|
|
1563
|
+
exc_instance = exc_type(exc_value)
|
|
1564
|
+
except:
|
|
1565
|
+
exc_instance = None
|
|
1566
|
+
|
|
1567
|
+
message += "".join(traceback.format_exception(exc_type, exc_instance, exc_traceback))
|
|
1568
|
+
caption = "PyXLL: " + ((context.error_type == ErrorContext.Type.MENU and "Menu") or "Ribbon") + " Error"
|
|
1569
|
+
# MB_SETFOREGROUND | MB_ICONHAND | MB_HELP
|
|
1570
|
+
message_box(message, caption, 0x00010000 | 0x00000010 | 0x00004000)
|
|
1571
|
+
return
|
|
1572
|
+
|
|
1573
|
+
if context.error_type == ErrorContext.Type.IMPORT:
|
|
1574
|
+
lines = ["Error importing Python modules"]
|
|
1575
|
+
if context.import_errors:
|
|
1576
|
+
lines.append("")
|
|
1577
|
+
for modulename, exc_info in context.import_errors:
|
|
1578
|
+
exc_type, exc_value, exc_traceback = exc_info
|
|
1579
|
+
lines.append("Error importing '%s': %s" % (modulename, exc_value))
|
|
1580
|
+
message = "\n".join(lines)
|
|
1581
|
+
# MB_SETFOREGROUND | MB_ICONHAND | MB_HELP
|
|
1582
|
+
message_box(message, "PyXLL: Error importing Python modules", 0x00010000 | 0x00000010 | 0x00004000)
|
|
1583
|
+
return
|
|
1584
|
+
|
|
1585
|
+
def error_handler_quiet(context, exc_type, exc_value, exc_traceback):
|
|
1586
|
+
"""PyXLL error handler that doesn't display any error dialogs"""
|
|
1587
|
+
# For UDFs return a preview of the error as a single line
|
|
1588
|
+
if context.error_type in (ErrorContext.Type.UDF, ErrorContext.Type.MACRO):
|
|
1589
|
+
error = "##" + getattr(exc_type, "__name__", "Error")
|
|
1590
|
+
msg = str(exc_value)
|
|
1591
|
+
if msg:
|
|
1592
|
+
error += ": " + msg
|
|
1593
|
+
return error
|
|
1594
|
+
|
|
1595
|
+
# for backwards compatibility with older pyxll.cfg files
|
|
1596
|
+
error_to_string = error_handler
|
|
1597
|
+
|
|
1598
|
+
def _wrap_iunknown(unk, no_dynamic_dispatch=False):
|
|
1599
|
+
"""Wrap a pythoncom PyIUnknown object into a win32com.Dispatch"""
|
|
1600
|
+
# Get the PyIDispatch object
|
|
1601
|
+
import pythoncom # type: ignore
|
|
1602
|
+
disp = unk.QueryInterface(pythoncom.IID_IDispatch)
|
|
1603
|
+
|
|
1604
|
+
# Try to wrap using the existing wrapper classes (or generate them if
|
|
1605
|
+
# they don't exist)
|
|
1606
|
+
try:
|
|
1607
|
+
from win32com.client.gencache import EnsureDispatch # type: ignore
|
|
1608
|
+
return EnsureDispatch(disp)
|
|
1609
|
+
except:
|
|
1610
|
+
if no_dynamic_dispatch:
|
|
1611
|
+
raise
|
|
1612
|
+
pass
|
|
1613
|
+
|
|
1614
|
+
# If we can't use a generated wrapper then use a dynamic Dispatch wrapper.
|
|
1615
|
+
# This will work but won't add constants to win32com.client.constants.
|
|
1616
|
+
import win32com # type: ignore
|
|
1617
|
+
_log.warning("win32com.client.Dispatch failed. win32com.client.dynamic.Dispatch will be used instead.")
|
|
1618
|
+
_log.warning("Delete your gen_py folder '%s' as it may have become corrupted" % win32com.__gen_path__)
|
|
1619
|
+
from win32com.client.dynamic import Dispatch as DynamicDispatch # type: ignore
|
|
1620
|
+
return DynamicDispatch(disp)
|
|
1621
|
+
|
|
1622
|
+
def _get_iunknown_package(unk):
|
|
1623
|
+
"""Return the com package the object is most likely to be from"""
|
|
1624
|
+
try:
|
|
1625
|
+
package = unk.__class__.__module__.split(".", 1)[0]
|
|
1626
|
+
if package in ("comtypes", "xlwings"):
|
|
1627
|
+
return package
|
|
1628
|
+
except AttributeError:
|
|
1629
|
+
pass
|
|
1630
|
+
|
|
1631
|
+
if hasattr(unk, "_oleobj_"):
|
|
1632
|
+
return "win32com"
|
|
1633
|
+
|
|
1634
|
+
return "pythoncom"
|
|
1635
|
+
|
|
1636
|
+
# Formatters
|
|
1637
|
+
|
|
1638
|
+
class BaseFormatter(object):
|
|
1639
|
+
"""Base class used for formatting Excel ranges.
|
|
1640
|
+
"""
|
|
1641
|
+
@classmethod
|
|
1642
|
+
def __get_numpy(cls):
|
|
1643
|
+
try:
|
|
1644
|
+
return cls.__np
|
|
1645
|
+
except AttributeError:
|
|
1646
|
+
try:
|
|
1647
|
+
import numpy # type: ignore
|
|
1648
|
+
cls.__np = numpy
|
|
1649
|
+
except ImportError:
|
|
1650
|
+
cls.__np = None
|
|
1651
|
+
return cls.__np
|
|
1652
|
+
|
|
1653
|
+
@classmethod
|
|
1654
|
+
def __is_sequence(cls, x):
|
|
1655
|
+
np = cls.__get_numpy()
|
|
1656
|
+
if np:
|
|
1657
|
+
return isinstance(x, (list, tuple, np.ndarray))
|
|
1658
|
+
return isinstance(x, (list, tuple))
|
|
1659
|
+
|
|
1660
|
+
@classmethod
|
|
1661
|
+
def __resize_array(cls, value, cell, datatype, datatype_ndim, transpose):
|
|
1662
|
+
# If the data type is object, and it's not an array, don't check if the object
|
|
1663
|
+
# is a sequence just convert it to a 1x1 array.
|
|
1664
|
+
if datatype == "object" and datatype_ndim == 0:
|
|
1665
|
+
value = [[value]]
|
|
1666
|
+
|
|
1667
|
+
# If the data type is a 1d array convert it to 1xN row array
|
|
1668
|
+
if datatype_ndim == 1:
|
|
1669
|
+
value = [value]
|
|
1670
|
+
|
|
1671
|
+
# Make sure the value is a 2d array
|
|
1672
|
+
if not cls.__is_sequence(value):
|
|
1673
|
+
value = [value]
|
|
1674
|
+
if len(value) == 0:
|
|
1675
|
+
value = [[None]]
|
|
1676
|
+
if not cls.__is_sequence(value[0]):
|
|
1677
|
+
value = [value]
|
|
1678
|
+
|
|
1679
|
+
# Transpose the array before matching it to the cell range
|
|
1680
|
+
if transpose:
|
|
1681
|
+
value = list(zip(*value))
|
|
1682
|
+
|
|
1683
|
+
# Pad or trim the array to match the cell range
|
|
1684
|
+
num_rows = cell.rows
|
|
1685
|
+
num_cols = cell.columns
|
|
1686
|
+
new_value = [None] * num_rows
|
|
1687
|
+
for r in range(num_rows):
|
|
1688
|
+
row = []
|
|
1689
|
+
if r < len(value):
|
|
1690
|
+
row = value[r]
|
|
1691
|
+
if len(row) > num_cols:
|
|
1692
|
+
row = row[:num_cols]
|
|
1693
|
+
if len(row) < num_cols:
|
|
1694
|
+
row = list(row) + ([None] * (num_cols - len(row)))
|
|
1695
|
+
new_value[r] = row
|
|
1696
|
+
|
|
1697
|
+
return new_value
|
|
1698
|
+
|
|
1699
|
+
def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
|
|
1700
|
+
"""Apply formatting to a cell or range of cells.
|
|
1701
|
+
|
|
1702
|
+
:param cell: XLCell instance to by formatted.
|
|
1703
|
+
:param value: Value being set on the cell(s).
|
|
1704
|
+
:param datatype: Data-type as specified as the return type when using @xl_func.
|
|
1705
|
+
:param datatype_ndim: Number of dimensions if the datatype is an array.
|
|
1706
|
+
:param datatype_kwargs: Data-type keyword arguments.
|
|
1707
|
+
:param transpose: True if the value should be transposed before styling.
|
|
1708
|
+
"""
|
|
1709
|
+
if self.apply_cell is not BaseFormatter.apply_cell:
|
|
1710
|
+
value = self.__resize_array(value, cell, datatype, datatype_ndim, transpose)
|
|
1711
|
+
for i, row_value in enumerate(value):
|
|
1712
|
+
for j, cell_value in enumerate(row_value):
|
|
1713
|
+
self.apply_cell(cell.cell(i, j),
|
|
1714
|
+
cell_value,
|
|
1715
|
+
datatype=datatype,
|
|
1716
|
+
datatype_kwargs=datatype_kwargs)
|
|
1717
|
+
|
|
1718
|
+
@staticmethod
|
|
1719
|
+
def apply_cell(cell, value=None, datatype=None, datatype_kwargs={}):
|
|
1720
|
+
"""Called for each cell to apply any formatting.
|
|
1721
|
+
|
|
1722
|
+
For most Formatter classes this is the only method that needs to
|
|
1723
|
+
be overridden.
|
|
1724
|
+
|
|
1725
|
+
:param cell: XLCell instance to by formatted.
|
|
1726
|
+
:param value: Value being set on the cell(s).
|
|
1727
|
+
:param datatype: Data-type as specified as the return type when using @xl_func.
|
|
1728
|
+
:param datatype_kwargs: Data-type keyword arguments.
|
|
1729
|
+
"""
|
|
1730
|
+
pass
|
|
1731
|
+
|
|
1732
|
+
@staticmethod
|
|
1733
|
+
def clear(cell):
|
|
1734
|
+
"""Clears any formatting from a cell or range of cells."""
|
|
1735
|
+
r = cell.to_range()
|
|
1736
|
+
r.Style = "Normal"
|
|
1737
|
+
|
|
1738
|
+
@staticmethod
|
|
1739
|
+
def apply_if_nested():
|
|
1740
|
+
"""Return True if formatter is to be applied when the function appears inside a nested formula.
|
|
1741
|
+
If True and the formatter is applied to a nested function, the methods clear_nested and apply_nested
|
|
1742
|
+
will be called.
|
|
1743
|
+
"""
|
|
1744
|
+
return False
|
|
1745
|
+
|
|
1746
|
+
def apply_nested(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
|
|
1747
|
+
"""Apply formatting to a cell or range of cells.
|
|
1748
|
+
|
|
1749
|
+
Used when the formatting is being applied from a nested function and
|
|
1750
|
+
self.apply_if_nested() returned True.
|
|
1751
|
+
|
|
1752
|
+
:param cell: XLCell instance to by formatted.
|
|
1753
|
+
:param value: Value being set on the cell(s).
|
|
1754
|
+
:param datatype: Data-type as specified as the return type when using @xl_func.
|
|
1755
|
+
:param datatype_ndim: Number of dimensions if the datatype is an array.
|
|
1756
|
+
:param datatype_kwargs: Data-type keyword arguments.
|
|
1757
|
+
:param transpose: True if the value should be transposed before styling.
|
|
1758
|
+
"""
|
|
1759
|
+
return self.apply(cell,
|
|
1760
|
+
value=value,
|
|
1761
|
+
datatype=datatype,
|
|
1762
|
+
datatype_ndim=datatype_ndim,
|
|
1763
|
+
datatype_kwargs=datatype_kwargs,
|
|
1764
|
+
transpose=transpose)
|
|
1765
|
+
|
|
1766
|
+
def clear_nested(self, cell):
|
|
1767
|
+
"""Clears any formatting from a cell or range of cells.
|
|
1768
|
+
|
|
1769
|
+
Used when the formatting is being applied from a nested function and
|
|
1770
|
+
self.apply_if_nested() returned True.
|
|
1771
|
+
"""
|
|
1772
|
+
return self.clear(cell)
|
|
1773
|
+
|
|
1774
|
+
@staticmethod
|
|
1775
|
+
def rgb(red, green, blue):
|
|
1776
|
+
"""Return a color number from RGB values.
|
|
1777
|
+
Note Excel uses 'BGR' instead of the more usual RGB.
|
|
1778
|
+
"""
|
|
1779
|
+
return (red & 0xff) | ((green & 0xff) << 8) | ((blue & 0xff) << 16)
|
|
1780
|
+
|
|
1781
|
+
@staticmethod
|
|
1782
|
+
def apply_styles(cells, styles):
|
|
1783
|
+
"""Apply a formatting style dictionaries to list of cells."""
|
|
1784
|
+
for cell, style in zip(cells, styles):
|
|
1785
|
+
BaseFormatter.apply_style(cell, style)
|
|
1786
|
+
|
|
1787
|
+
@staticmethod
|
|
1788
|
+
def apply_style(cell, style):
|
|
1789
|
+
"""Apply a formatting style dictionary to a cell."""
|
|
1790
|
+
if not style:
|
|
1791
|
+
return
|
|
1792
|
+
|
|
1793
|
+
r = cell.to_range()
|
|
1794
|
+
interior_color = style.get("interior_color", None)
|
|
1795
|
+
if interior_color is not None:
|
|
1796
|
+
r.Interior.Color = interior_color
|
|
1797
|
+
|
|
1798
|
+
text_color = style.get("text_color", None)
|
|
1799
|
+
if text_color is not None:
|
|
1800
|
+
r.Font.Color = text_color
|
|
1801
|
+
|
|
1802
|
+
bold = style.get("bold", None)
|
|
1803
|
+
if bold is not None:
|
|
1804
|
+
r.Font.Bold = bold
|
|
1805
|
+
|
|
1806
|
+
italic = style.get("italic", None)
|
|
1807
|
+
if italic is not None:
|
|
1808
|
+
r.Font.Italic = italic
|
|
1809
|
+
|
|
1810
|
+
font_size = style.get("font_size", None)
|
|
1811
|
+
if font_size is not None:
|
|
1812
|
+
r.Font.Size = font_size
|
|
1813
|
+
|
|
1814
|
+
number_format = style.get("number_format", None)
|
|
1815
|
+
if number_format is not None:
|
|
1816
|
+
r.NumberFormat = number_format
|
|
1817
|
+
|
|
1818
|
+
auto_fit = style.get("auto_fit", False)
|
|
1819
|
+
if auto_fit:
|
|
1820
|
+
r.AutoFit()
|
|
1821
|
+
|
|
1822
|
+
class FormatterCollection(BaseFormatter):
|
|
1823
|
+
|
|
1824
|
+
def __init__(self, formatters=[]):
|
|
1825
|
+
self.__formatters = formatters
|
|
1826
|
+
|
|
1827
|
+
def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
|
|
1828
|
+
for formatter in self.__formatters:
|
|
1829
|
+
formatter.apply(cell,
|
|
1830
|
+
value,
|
|
1831
|
+
datatype=datatype,
|
|
1832
|
+
datatype_ndim=datatype_ndim,
|
|
1833
|
+
datatype_kwargs=datatype_kwargs,
|
|
1834
|
+
transpose=transpose)
|
|
1835
|
+
|
|
1836
|
+
def clear(self, cell):
|
|
1837
|
+
# Only call clear once unless implemented differently from the base class
|
|
1838
|
+
cleared = False
|
|
1839
|
+
for formatter in self.__formatters:
|
|
1840
|
+
if not cleared or formatter.clear is not BaseFormatter.clear:
|
|
1841
|
+
formatter.clear(cell)
|
|
1842
|
+
cleared = True
|
|
1843
|
+
|
|
1844
|
+
def clear_nested(self, *args, **kwargs):
|
|
1845
|
+
for formatter in self.__formatters:
|
|
1846
|
+
if formatter.apply_if_nested():
|
|
1847
|
+
formatter.clear(*args, **kwargs)
|
|
1848
|
+
|
|
1849
|
+
def apply_if_nested(self):
|
|
1850
|
+
for formatter in self.__formatters:
|
|
1851
|
+
if formatter.apply_if_nested():
|
|
1852
|
+
return True
|
|
1853
|
+
return False
|
|
1854
|
+
|
|
1855
|
+
def apply_nested(self, *args, **kwargs):
|
|
1856
|
+
for formatter in self.__formatters:
|
|
1857
|
+
if formatter.apply_if_nested():
|
|
1858
|
+
formatter.apply(*args, **kwargs)
|
|
1859
|
+
|
|
1860
|
+
def __add__(self, other):
|
|
1861
|
+
if isinstance(other, dict):
|
|
1862
|
+
other = Formatter(**other)
|
|
1863
|
+
if not isinstance(other, BaseFormatter):
|
|
1864
|
+
raise TypeError("Can't add non-formatter object to a formatter.")
|
|
1865
|
+
return FormatterCollection(self.__formatters + [other])
|
|
1866
|
+
|
|
1867
|
+
def __iadd__(self, other):
|
|
1868
|
+
if isinstance(other, dict):
|
|
1869
|
+
other = Formatter(**other)
|
|
1870
|
+
if not isinstance(other, BaseFormatter):
|
|
1871
|
+
raise TypeError("Can't add non-formatter object to a formatter.")
|
|
1872
|
+
self.__formatters.append(other)
|
|
1873
|
+
return self
|
|
1874
|
+
|
|
1875
|
+
class Formatter(BaseFormatter):
|
|
1876
|
+
"""Formatter for formatting values returned via xl_func, or using XLCell.options.
|
|
1877
|
+
|
|
1878
|
+
Use Formatter.rgb(red, green, blue) for constructing color values.
|
|
1879
|
+
|
|
1880
|
+
Formatters may be combined by adding them together.
|
|
1881
|
+
|
|
1882
|
+
:param interior_color: Value to set the interior color to.
|
|
1883
|
+
:param text_color: Value to set the text color to.
|
|
1884
|
+
:param bold: If true, sent the text style to bold.
|
|
1885
|
+
:param italic: If true, sent the text style to italic.
|
|
1886
|
+
:param font_size: Value to set the font size to.
|
|
1887
|
+
:param number_format: Excel number format to use.
|
|
1888
|
+
:param auto_fit: Auto-fit to the content of the cells. May be True (fit column width),
|
|
1889
|
+
False (don't fit), 'columns' (fit column width), 'rows' (fit row width),
|
|
1890
|
+
'both' (fit column and row width).
|
|
1891
|
+
"""
|
|
1892
|
+
|
|
1893
|
+
def __init__(self,
|
|
1894
|
+
interior_color=None,
|
|
1895
|
+
text_color=None,
|
|
1896
|
+
bold=None,
|
|
1897
|
+
italic=None,
|
|
1898
|
+
font_size=None,
|
|
1899
|
+
number_format=None,
|
|
1900
|
+
auto_fit=None):
|
|
1901
|
+
BaseFormatter.__init__(self)
|
|
1902
|
+
self.__style = {}
|
|
1903
|
+
if interior_color is not None:
|
|
1904
|
+
self.__style["interior_color"] = interior_color
|
|
1905
|
+
if text_color is not None:
|
|
1906
|
+
self.__style["text_color"] = text_color
|
|
1907
|
+
if bold is not None:
|
|
1908
|
+
self.__style["bold"] = bold
|
|
1909
|
+
if italic is not None:
|
|
1910
|
+
self.__style["italic"] = italic
|
|
1911
|
+
if font_size is not None:
|
|
1912
|
+
self.__style["font_size"] = font_size
|
|
1913
|
+
if number_format is not None:
|
|
1914
|
+
self.__style["number_format"] = number_format
|
|
1915
|
+
if auto_fit is not None:
|
|
1916
|
+
self.__style["auto_fit"] = auto_fit
|
|
1917
|
+
|
|
1918
|
+
def __add__(self, other):
|
|
1919
|
+
if type(self) == type(other) == Formatter:
|
|
1920
|
+
style = dict(self.__style)
|
|
1921
|
+
style.update(other.__style)
|
|
1922
|
+
return Formatter(**style)
|
|
1923
|
+
elif isinstance(other, dict):
|
|
1924
|
+
return self + Formatter(**other)
|
|
1925
|
+
elif not isinstance(other, BaseFormatter):
|
|
1926
|
+
raise TypeError("Can't add non-formatter object to a formatter.")
|
|
1927
|
+
return FormatterCollection([self, other])
|
|
1928
|
+
|
|
1929
|
+
def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
|
|
1930
|
+
# Update the style to the range
|
|
1931
|
+
self.apply_style(cell, self.__style)
|
|
1932
|
+
|
|
1933
|
+
# Apply any styles from the base class (this handles calling apply_cell if necessary
|
|
1934
|
+
# and so should be done after applying the main style to the whold range).
|
|
1935
|
+
BaseFormatter.apply(self,
|
|
1936
|
+
cell,
|
|
1937
|
+
value,
|
|
1938
|
+
datatype=datatype,
|
|
1939
|
+
datatype_ndim=datatype_ndim,
|
|
1940
|
+
datatype_kwargs=datatype_kwargs,
|
|
1941
|
+
transpose=transpose)
|
|
1942
|
+
|
|
1943
|
+
class DateFormatter(Formatter):
|
|
1944
|
+
"""Formatter for dates, times and datetimes.
|
|
1945
|
+
|
|
1946
|
+
All formats are in the standard Python datetime format.
|
|
1947
|
+
|
|
1948
|
+
This formatter tests the values and applies the relevant
|
|
1949
|
+
number format according to the type.
|
|
1950
|
+
|
|
1951
|
+
:param date_format: Format used for date values.
|
|
1952
|
+
:param time_format: Format used for time values.
|
|
1953
|
+
:param datetime_format: Format used for datetime values.
|
|
1954
|
+
"""
|
|
1955
|
+
|
|
1956
|
+
def __init__(self,
|
|
1957
|
+
date_format="%Y-%m-%d",
|
|
1958
|
+
time_format="%H:%M:%S",
|
|
1959
|
+
datetime_format=None,
|
|
1960
|
+
**kwargs):
|
|
1961
|
+
Formatter.__init__(self, **kwargs)
|
|
1962
|
+
|
|
1963
|
+
# Convert the Python date format to an Excel number format
|
|
1964
|
+
if not datetime_format:
|
|
1965
|
+
datetime_format = "%s %s" % (date_format, time_format)
|
|
1966
|
+
self.__date_number_format = self.__to_number_format(date_format)
|
|
1967
|
+
self.__time_number_formmat = self.__to_number_format(time_format)
|
|
1968
|
+
self.__datetimetime_number_formmat = self.__to_number_format(datetime_format)
|
|
1969
|
+
|
|
1970
|
+
@staticmethod
|
|
1971
|
+
def __to_number_format(date_format):
|
|
1972
|
+
"""Convert a Python date format to an Excel number format."""
|
|
1973
|
+
number_format = date_format.replace("%Y", "yyyy")
|
|
1974
|
+
number_format = number_format.replace("%y", "yy")
|
|
1975
|
+
number_format = number_format.replace("%m", "mm")
|
|
1976
|
+
number_format = number_format.replace("%b", "mmm")
|
|
1977
|
+
number_format = number_format.replace("%d", "dd")
|
|
1978
|
+
number_format = number_format.replace("%H", "hh")
|
|
1979
|
+
number_format = number_format.replace("%M", "mm")
|
|
1980
|
+
number_format = number_format.replace("%S", "ss")
|
|
1981
|
+
return number_format
|
|
1982
|
+
|
|
1983
|
+
def apply_cell(self, cell, value=None, datatype=None, datatype_kwargs={}):
|
|
1984
|
+
"""Apply the relevant formatting."""
|
|
1985
|
+
if datatype is None or "var":
|
|
1986
|
+
if isinstance(value, datetime.datetime):
|
|
1987
|
+
datatype = "datetime"
|
|
1988
|
+
elif isinstance(value, datetime.date):
|
|
1989
|
+
datatype = "date"
|
|
1990
|
+
elif isinstance(value, datetime.time):
|
|
1991
|
+
datatype = "time"
|
|
1992
|
+
|
|
1993
|
+
number_format = None
|
|
1994
|
+
if datatype == "datetime":
|
|
1995
|
+
number_format = self.__datetimetime_number_formmat
|
|
1996
|
+
elif datatype == "date":
|
|
1997
|
+
number_format = self.__date_number_format
|
|
1998
|
+
elif datatype == "time":
|
|
1999
|
+
number_format = self.__time_number_formmat
|
|
2000
|
+
|
|
2001
|
+
if number_format is not None:
|
|
2002
|
+
self.apply_style(cell, {"number_format": number_format})
|
|
2003
|
+
|
|
2004
|
+
class ConditionalFormatterBase:
|
|
2005
|
+
|
|
2006
|
+
def get_formatters(self, df):
|
|
2007
|
+
"""Return a DataFrame the same dimensions as 'df' with the values
|
|
2008
|
+
set to a 'Formatter' where formatting should be applied and False
|
|
2009
|
+
or None otherwise.
|
|
2010
|
+
"""
|
|
2011
|
+
raise NotImplementedError()
|
|
2012
|
+
|
|
2013
|
+
class ConditionalFormatter(ConditionalFormatterBase):
|
|
2014
|
+
|
|
2015
|
+
def __init__(self, expr, formatter, columns=None, **kwargs):
|
|
2016
|
+
"""
|
|
2017
|
+
A ConditionalFormatter for use with DataFrameFormatter.
|
|
2018
|
+
|
|
2019
|
+
:param expr: Boolean expression for selecting rows to which the formatter will apply.
|
|
2020
|
+
:param formatter: Formatter that will be applied to the selected cells.
|
|
2021
|
+
:param columns: Column name or list of columns that the formatter will be applied to.
|
|
2022
|
+
May also be a callable, in which case it should accept a DataFrame and
|
|
2023
|
+
return a column or list of columns.
|
|
2024
|
+
:param kwargs: Additional arguments passed to DataFrame.eval when selecting the rows
|
|
2025
|
+
to apply the formatter to.
|
|
2026
|
+
"""
|
|
2027
|
+
if "inplace" in kwargs:
|
|
2028
|
+
raise TypeError("inplace is an invalid keyword argument for ConditionalFormatter.")
|
|
2029
|
+
self.__expr = expr
|
|
2030
|
+
self.__columns = columns
|
|
2031
|
+
self.__kwargs = kwargs
|
|
2032
|
+
|
|
2033
|
+
if isinstance(formatter, dict):
|
|
2034
|
+
formatter = Formatter(**formatter)
|
|
2035
|
+
self.__formatter = formatter
|
|
2036
|
+
|
|
2037
|
+
def get_formatters(self, df):
|
|
2038
|
+
"""See ConditionalFormatterBase.get_formatters"""
|
|
2039
|
+
# Create an empty DataFrame the same size as the source
|
|
2040
|
+
pd, np = _pandas_get_imports()
|
|
2041
|
+
formatters_df = pd.DataFrame(False, index=df.index, columns=df.columns, dtype=object)
|
|
2042
|
+
|
|
2043
|
+
# Query which rows should be included
|
|
2044
|
+
row_mask = df.eval(self.__expr, **self.__kwargs)
|
|
2045
|
+
if not row_mask.any():
|
|
2046
|
+
return None
|
|
2047
|
+
|
|
2048
|
+
col_mask = None
|
|
2049
|
+
if self.__columns:
|
|
2050
|
+
def _update_col_mask(col, col_mask):
|
|
2051
|
+
if callable(col):
|
|
2052
|
+
col = col(df)
|
|
2053
|
+
_update_col_mask(col, col_mask)
|
|
2054
|
+
elif isinstance(col, (list, tuple)):
|
|
2055
|
+
for c in col:
|
|
2056
|
+
_update_col_mask(c, col_mask)
|
|
2057
|
+
else:
|
|
2058
|
+
if col not in col_mask.index:
|
|
2059
|
+
raise RuntimeError("Invalid column '%s' found when applying conditional formatting." % str(col))
|
|
2060
|
+
col_mask[col] = True
|
|
2061
|
+
|
|
2062
|
+
col_mask = pd.Series(False, index=df.columns)
|
|
2063
|
+
_update_col_mask(self.__columns, col_mask)
|
|
2064
|
+
|
|
2065
|
+
if col_mask is None:
|
|
2066
|
+
formatters_df.loc[row_mask] = self.__formatter
|
|
2067
|
+
return formatters_df
|
|
2068
|
+
|
|
2069
|
+
formatters_df.loc[row_mask, col_mask] = self.__formatter
|
|
2070
|
+
return formatters_df
|
|
2071
|
+
|
|
2072
|
+
class DataFrameFormatter(Formatter):
|
|
2073
|
+
"""Formatter for DataFrames.
|
|
2074
|
+
|
|
2075
|
+
For each argument expecting a Formatter, a dict may also be provided.
|
|
2076
|
+
|
|
2077
|
+
When a list of formatters is used (e.g. for the row or index formatters)
|
|
2078
|
+
the formatters will cycle through the list and repeat. For example, to
|
|
2079
|
+
format a table with striped rows only two row formatters are needed.
|
|
2080
|
+
|
|
2081
|
+
:param rows: Formatter or list of formatters to be applied to the rows.
|
|
2082
|
+
:param header: Formatter to use for the header column names.
|
|
2083
|
+
:param index: Formatter or list of formatters to be applied to the index.
|
|
2084
|
+
:param columns: Dict of column name to formatter or list of formatters to
|
|
2085
|
+
be applied for specific columns (in addition to the any
|
|
2086
|
+
row formatters).
|
|
2087
|
+
:param conditional_formatters: A list of ConditionalFormatters to be applied
|
|
2088
|
+
in order after any other formatting has
|
|
2089
|
+
been applied.
|
|
2090
|
+
:param kwargs: Additional Formatter kwargs that will affect the entire
|
|
2091
|
+
formatted range.
|
|
2092
|
+
"""
|
|
2093
|
+
|
|
2094
|
+
default_header_formatter = Formatter(interior_color=0x8ED0A9)
|
|
2095
|
+
|
|
2096
|
+
default_index_formatter = Formatter(interior_color=0x8ED0A9)
|
|
2097
|
+
|
|
2098
|
+
default_row_formatters = [
|
|
2099
|
+
Formatter(interior_color=0xDBF1E4),
|
|
2100
|
+
Formatter(interior_color=0xF1F9F4),
|
|
2101
|
+
]
|
|
2102
|
+
|
|
2103
|
+
def __init__(self,
|
|
2104
|
+
rows=default_row_formatters,
|
|
2105
|
+
header=default_header_formatter,
|
|
2106
|
+
index=default_index_formatter,
|
|
2107
|
+
columns=None,
|
|
2108
|
+
conditional_formatters=None,
|
|
2109
|
+
**kwargs):
|
|
2110
|
+
Formatter.__init__(self, **kwargs)
|
|
2111
|
+
|
|
2112
|
+
# row is a list of formatters to be used for each row in the DataFrame
|
|
2113
|
+
self.__row_formatters = None
|
|
2114
|
+
if rows:
|
|
2115
|
+
if not isinstance(rows, (list, tuple)):
|
|
2116
|
+
rows = [rows]
|
|
2117
|
+
self.__row_formatters = []
|
|
2118
|
+
for formatter in rows:
|
|
2119
|
+
formatter = self.__to_formatter(formatter)
|
|
2120
|
+
self.__row_formatters.append(formatter)
|
|
2121
|
+
|
|
2122
|
+
self.__header_formatter = None
|
|
2123
|
+
if header:
|
|
2124
|
+
self.__header_formatter = self.__to_formatter(header)
|
|
2125
|
+
|
|
2126
|
+
# index is a list of formatters to be used for each row in the index
|
|
2127
|
+
self.__index_formatters = None
|
|
2128
|
+
if index:
|
|
2129
|
+
if not isinstance(index, (list, tuple)):
|
|
2130
|
+
index = [index]
|
|
2131
|
+
self.__index_formatters = []
|
|
2132
|
+
for formatter in index:
|
|
2133
|
+
formatter = self.__to_formatter(formatter)
|
|
2134
|
+
self.__index_formatters.append(formatter)
|
|
2135
|
+
|
|
2136
|
+
# columns is a dict of columns to formatters or list of formatters
|
|
2137
|
+
self.__column_formatters = None
|
|
2138
|
+
if columns:
|
|
2139
|
+
if not isinstance(columns, dict):
|
|
2140
|
+
raise TypeError("Expected 'columns' to be a dict of formatters")
|
|
2141
|
+
|
|
2142
|
+
self.__column_formatters = {}
|
|
2143
|
+
for key, formatters in list(columns.items()):
|
|
2144
|
+
if not isinstance(formatters, list):
|
|
2145
|
+
formatters = [formatters]
|
|
2146
|
+
self.__column_formatters[key] = []
|
|
2147
|
+
for formatter in formatters:
|
|
2148
|
+
formatter = self.__to_formatter(formatter)
|
|
2149
|
+
self.__column_formatters[key].append(formatter)
|
|
2150
|
+
|
|
2151
|
+
# Conditional formatters is a list of formatters to be applied in order
|
|
2152
|
+
self.__conditional_formatters = []
|
|
2153
|
+
if conditional_formatters is not None and not isinstance(conditional_formatters, (list, tuple)):
|
|
2154
|
+
raise TypeError("Expected 'conditional_formatters' to be a list of ConditionalFormatters")
|
|
2155
|
+
if conditional_formatters:
|
|
2156
|
+
for formatter in conditional_formatters:
|
|
2157
|
+
if isinstance(formatter, tuple):
|
|
2158
|
+
formatter = ConditionalFormatter(*formatter)
|
|
2159
|
+
elif isinstance(formatter, dict):
|
|
2160
|
+
formatter = ConditionalFormatter(**formatter)
|
|
2161
|
+
if not isinstance(formatter, ConditionalFormatterBase):
|
|
2162
|
+
raise TypeError("Expected 'conditional_formatters' to be a list of ConditionalFormatters")
|
|
2163
|
+
self.__conditional_formatters.append(formatter)
|
|
2164
|
+
|
|
2165
|
+
@staticmethod
|
|
2166
|
+
def __to_formatter(formatter):
|
|
2167
|
+
"""helper to convert dict to formatter"""
|
|
2168
|
+
if isinstance(formatter, dict):
|
|
2169
|
+
formatter = Formatter(**formatter)
|
|
2170
|
+
return formatter
|
|
2171
|
+
|
|
2172
|
+
def apply(self, cell, value=None, datatype=None, datatype_ndim=0, datatype_kwargs={}, transpose=False):
|
|
2173
|
+
Formatter.apply(self,
|
|
2174
|
+
cell,
|
|
2175
|
+
value=value,
|
|
2176
|
+
datatype=datatype,
|
|
2177
|
+
datatype_ndim=datatype_ndim,
|
|
2178
|
+
datatype_kwargs=datatype_kwargs,
|
|
2179
|
+
transpose=transpose)
|
|
2180
|
+
|
|
2181
|
+
type_desc = TypeDescriptor.create(datatype, kwargs=datatype_kwargs)
|
|
2182
|
+
if (("pandas.dataframe" not in type_desc.return_base_type_names
|
|
2183
|
+
and "dataframe" not in type_desc.return_base_type_names)
|
|
2184
|
+
or datatype_ndim != 0):
|
|
2185
|
+
_log.warning("DataFrameFormatter applied to a function without return type pandas.DataFrame: %s" % str(type_desc))
|
|
2186
|
+
return
|
|
2187
|
+
|
|
2188
|
+
pd, np = _pandas_get_imports()
|
|
2189
|
+
if not isinstance(value, pd.DataFrame):
|
|
2190
|
+
_log.warning("DataFrameFormatter applied to a non-pandas.DataFrame result: %s" % type(value))
|
|
2191
|
+
return
|
|
2192
|
+
|
|
2193
|
+
df = value
|
|
2194
|
+
df_to_array = get_type_converter(datatype, "__internal__", src_kwargs=datatype_kwargs)
|
|
2195
|
+
df_array = df_to_array(value)
|
|
2196
|
+
|
|
2197
|
+
header_rows = 0
|
|
2198
|
+
if datatype_kwargs.get("columns", True):
|
|
2199
|
+
header_rows = 1
|
|
2200
|
+
if isinstance(df.columns, pd.MultiIndex):
|
|
2201
|
+
header_rows = len(df.columns.levels)
|
|
2202
|
+
|
|
2203
|
+
index_cols = 0
|
|
2204
|
+
if datatype_kwargs.get("index", False):
|
|
2205
|
+
index_cols = 1
|
|
2206
|
+
if isinstance(df.index, pd.MultiIndex):
|
|
2207
|
+
index_cols = len(df.index.levels)
|
|
2208
|
+
|
|
2209
|
+
num_rows = len(df.index)
|
|
2210
|
+
num_cols = len(df.columns)
|
|
2211
|
+
|
|
2212
|
+
# Make sure the area we format is within the original range
|
|
2213
|
+
if transpose:
|
|
2214
|
+
max_rows = cell.columns
|
|
2215
|
+
max_cols = cell.rows
|
|
2216
|
+
else:
|
|
2217
|
+
max_rows = cell.rows
|
|
2218
|
+
max_cols = cell.columns
|
|
2219
|
+
|
|
2220
|
+
if (num_rows + header_rows) > max_rows:
|
|
2221
|
+
diff = (num_rows + header_rows) - max_rows
|
|
2222
|
+
deleted_rows = min(num_rows, diff)
|
|
2223
|
+
num_rows -= deleted_rows
|
|
2224
|
+
diff -= deleted_rows
|
|
2225
|
+
header_rows -= min(header_rows, diff)
|
|
2226
|
+
|
|
2227
|
+
if (num_cols + index_cols) > max_cols:
|
|
2228
|
+
diff = (num_cols + index_cols) - max_cols
|
|
2229
|
+
deleted_cols = min(diff, num_cols)
|
|
2230
|
+
num_cols -= deleted_cols
|
|
2231
|
+
diff -= deleted_cols
|
|
2232
|
+
index_cols -= min(index_cols, diff)
|
|
2233
|
+
|
|
2234
|
+
# Helper for transposing a range relative to the root range
|
|
2235
|
+
def _transpose(range, transpose):
|
|
2236
|
+
if not transpose:
|
|
2237
|
+
return range
|
|
2238
|
+
r = range.rect.first_row - cell.rect.first_row
|
|
2239
|
+
c = range.rect.first_col - cell.rect.first_col
|
|
2240
|
+
return cell.offset(c, r).resize(range.columns, range.rows)
|
|
2241
|
+
|
|
2242
|
+
if self.__header_formatter and header_rows and (num_cols or index_cols):
|
|
2243
|
+
header_range = cell.resize(header_rows, num_cols + index_cols)
|
|
2244
|
+
self.__header_formatter.apply(_transpose(header_range, transpose),
|
|
2245
|
+
df_array[:header_rows],
|
|
2246
|
+
datatype="var",
|
|
2247
|
+
datatype_ndim=2,
|
|
2248
|
+
transpose=transpose)
|
|
2249
|
+
|
|
2250
|
+
if self.__row_formatters and num_rows and (num_cols or index_cols):
|
|
2251
|
+
if len(self.__row_formatters) == 1:
|
|
2252
|
+
rows_range = cell.offset(header_rows, 0).resize(num_rows, num_cols + index_cols)
|
|
2253
|
+
formatter = self.__row_formatters[0]
|
|
2254
|
+
formatter.apply(_transpose(rows_range, transpose),
|
|
2255
|
+
df_array[header_rows:num_rows+header_rows],
|
|
2256
|
+
datatype="var",
|
|
2257
|
+
datatype_ndim=2,
|
|
2258
|
+
transpose=transpose)
|
|
2259
|
+
else:
|
|
2260
|
+
for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
|
|
2261
|
+
row_range = cell.offset(i + header_rows, 0).resize(1, num_cols + index_cols)
|
|
2262
|
+
formatter = self.__row_formatters[i % len(self.__row_formatters)]
|
|
2263
|
+
formatter.apply(_transpose(row_range, transpose),
|
|
2264
|
+
df_array[i+header_rows],
|
|
2265
|
+
datatype="var",
|
|
2266
|
+
datatype_ndim=1,
|
|
2267
|
+
transpose=transpose)
|
|
2268
|
+
|
|
2269
|
+
if self.__index_formatters and index_cols and num_rows:
|
|
2270
|
+
if len(self.__index_formatters) == 1:
|
|
2271
|
+
index_range = cell.offset(header_rows, 0).resize(num_rows, index_cols)
|
|
2272
|
+
formatter = self.__index_formatters[0]
|
|
2273
|
+
formatter.apply(_transpose(index_range, transpose),
|
|
2274
|
+
[x[:index_cols] for x in df_array[header_rows:num_rows+header_rows]],
|
|
2275
|
+
datatype="var",
|
|
2276
|
+
datatype_ndim=2,
|
|
2277
|
+
transpose=transpose)
|
|
2278
|
+
else:
|
|
2279
|
+
for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
|
|
2280
|
+
index_range = cell.offset(i + header_rows, 0).resize(1, index_cols)
|
|
2281
|
+
formatter = self.__index_formatters[i % len(self.__index_formatters)]
|
|
2282
|
+
formatter.apply(_transpose(index_range, transpose),
|
|
2283
|
+
df_array[i+header_rows][:index_cols],
|
|
2284
|
+
datatype="var",
|
|
2285
|
+
datatype_ndim=1,
|
|
2286
|
+
transpose=transpose)
|
|
2287
|
+
|
|
2288
|
+
if self.__column_formatters and num_rows:
|
|
2289
|
+
for col, formatters in list(self.__column_formatters.items()):
|
|
2290
|
+
try:
|
|
2291
|
+
col_idx = df.columns.get_loc(col)
|
|
2292
|
+
except KeyError:
|
|
2293
|
+
continue
|
|
2294
|
+
|
|
2295
|
+
if col_idx >= num_cols:
|
|
2296
|
+
continue
|
|
2297
|
+
|
|
2298
|
+
if len(formatters) == 1:
|
|
2299
|
+
col_range = cell.offset(header_rows, col_idx + index_cols).resize(num_rows, 1)
|
|
2300
|
+
formatter = formatters[0]
|
|
2301
|
+
formatter.apply(_transpose(col_range, transpose),
|
|
2302
|
+
[[x[col_idx+index_cols]] for x in df_array[header_rows:num_rows+header_rows]],
|
|
2303
|
+
datatype="var",
|
|
2304
|
+
datatype_ndim=2,
|
|
2305
|
+
transpose=transpose)
|
|
2306
|
+
else:
|
|
2307
|
+
for i, row in enumerate(df_array[header_rows:num_rows+header_rows]):
|
|
2308
|
+
cel_range = cell.offset(i + header_rows, col_idx + index_cols)
|
|
2309
|
+
formatter = formatters[i % len(formatters)]
|
|
2310
|
+
formatter.apply(_transpose(cel_range, transpose),
|
|
2311
|
+
df_array[header_rows+i][col_idx+index_cols],
|
|
2312
|
+
datatype="var",
|
|
2313
|
+
datatype_ndim=0,
|
|
2314
|
+
transpose=transpose)
|
|
2315
|
+
|
|
2316
|
+
# Apply the conditional formatters if there are any
|
|
2317
|
+
if self.__conditional_formatters and num_rows:
|
|
2318
|
+
to_array = get_type_converter("pandas.dataframe", "__internal__", src_kwargs={"index": False, "columns": False})
|
|
2319
|
+
for conditional_formatter in self.__conditional_formatters:
|
|
2320
|
+
formatter_df = conditional_formatter.get_formatters(df)
|
|
2321
|
+
if formatter_df is None:
|
|
2322
|
+
continue
|
|
2323
|
+
|
|
2324
|
+
if df.shape != formatter_df.shape:
|
|
2325
|
+
raise RuntimeError("A ConditionalFormatter returned a DataFrame of the wrong shape.")
|
|
2326
|
+
|
|
2327
|
+
formatter_array = to_array(formatter_df)
|
|
2328
|
+
for r, row in enumerate(formatter_array[:num_rows]):
|
|
2329
|
+
for c, formatter in enumerate(row[:num_cols]):
|
|
2330
|
+
if not formatter or pd.isnull(formatter):
|
|
2331
|
+
continue
|
|
2332
|
+
|
|
2333
|
+
formatter = self.__to_formatter(formatter)
|
|
2334
|
+
cell_to_format = cell.offset(header_rows + r, index_cols + c)
|
|
2335
|
+
formatter.apply(_transpose(cell_to_format, transpose),
|
|
2336
|
+
df_array[header_rows + r][index_cols + c],
|
|
2337
|
+
datatype="var",
|
|
2338
|
+
datatype_ndim=0,
|
|
2339
|
+
transpose=transpose)
|
|
2340
|
+
|
|
2341
|
+
# Custom task panes and ActiveX controls
|
|
2342
|
+
|
|
2343
|
+
class UIBridge:
|
|
2344
|
+
"""Base class of bridges between the Python UI toolkits
|
|
2345
|
+
and PyXLL's Custom Task Panes.
|
|
2346
|
+
"""
|
|
2347
|
+
|
|
2348
|
+
def __init__(self, control):
|
|
2349
|
+
self.__timer_interval = 0.1
|
|
2350
|
+
self.__has_focus = False
|
|
2351
|
+
self.control = control
|
|
2352
|
+
|
|
2353
|
+
def close(self):
|
|
2354
|
+
pass
|
|
2355
|
+
|
|
2356
|
+
def get_hwnd(self):
|
|
2357
|
+
raise NotImplemented()
|
|
2358
|
+
|
|
2359
|
+
def pre_attach(self, hwnd):
|
|
2360
|
+
pass
|
|
2361
|
+
|
|
2362
|
+
def post_attach(self, hwnd):
|
|
2363
|
+
pass
|
|
2364
|
+
|
|
2365
|
+
def on_close(self):
|
|
2366
|
+
pass
|
|
2367
|
+
|
|
2368
|
+
def on_window_closed(self):
|
|
2369
|
+
pass
|
|
2370
|
+
|
|
2371
|
+
def on_window_destroyed(self):
|
|
2372
|
+
pass
|
|
2373
|
+
|
|
2374
|
+
def process_message(self, hwnd, msg, wparam, lparam):
|
|
2375
|
+
pass
|
|
2376
|
+
|
|
2377
|
+
def translate_accelerator(self, hwnd, msg, wparam, lparam, modifier):
|
|
2378
|
+
pass
|
|
2379
|
+
|
|
2380
|
+
def filter_message(self, hwnd, msg, wparam, lparam):
|
|
2381
|
+
pass
|
|
2382
|
+
|
|
2383
|
+
def __set_has_focus(self, has_focus):
|
|
2384
|
+
self.__has_focus = has_focus
|
|
2385
|
+
|
|
2386
|
+
def __get_has_focus(self):
|
|
2387
|
+
return self.__has_focus
|
|
2388
|
+
|
|
2389
|
+
has_focus = property(__get_has_focus, __set_has_focus)
|
|
2390
|
+
|
|
2391
|
+
def __set_timer_interval(self, interval):
|
|
2392
|
+
self.__timer_interval = interval
|
|
2393
|
+
|
|
2394
|
+
def __get_timer_interval(self):
|
|
2395
|
+
return self.__timer_interval
|
|
2396
|
+
|
|
2397
|
+
timer_interval = property(__get_timer_interval, __set_timer_interval)
|
|
2398
|
+
|
|
2399
|
+
def on_timer(self):
|
|
2400
|
+
pass
|
|
2401
|
+
|
|
2402
|
+
CTPDockPositionLeft = 0
|
|
2403
|
+
CTPDockPositionTop = 1
|
|
2404
|
+
CTPDockPositionRight = 2
|
|
2405
|
+
CTPDockPositionBottom = 3
|
|
2406
|
+
CTPDockPositionFloating = 4
|
|
2407
|
+
|
|
2408
|
+
CTPDockPositionRestrictNone = 0
|
|
2409
|
+
CTPDockPositionRestrictNoChange = 1
|
|
2410
|
+
CTPDockPositionRestrictNoHorizontal = 2
|
|
2411
|
+
CTPDockPositionRestrictNoVertical = 3
|
|
2412
|
+
|
|
2413
|
+
class CTPBridgeBase(UIBridge):
|
|
2414
|
+
"""Base class of bridges between the Python UI toolkits
|
|
2415
|
+
and PyXLL's Custom Task Panes.
|
|
2416
|
+
"""
|
|
2417
|
+
|
|
2418
|
+
def get_title(self):
|
|
2419
|
+
pass
|
|
2420
|
+
|
|
2421
|
+
def xl_ctp_bridge(*clsnames):
|
|
2422
|
+
"""Decorator to apply to implementations of the CTPBridgeBase class
|
|
2423
|
+
to register that class as the default bridge for a UI control.
|
|
2424
|
+
|
|
2425
|
+
For example::
|
|
2426
|
+
|
|
2427
|
+
@xl_ctp_bridge("myuilib.Widget")
|
|
2428
|
+
class MyUIBridge(CTPBridgeBase):
|
|
2429
|
+
...
|
|
2430
|
+
|
|
2431
|
+
After registering a bridge class, any call to `pyxll.create_ctp`
|
|
2432
|
+
with an object of the types specified will use the registered bridge.
|
|
2433
|
+
"""
|
|
2434
|
+
def xl_ctp_bridge_decorator(bridge_cls):
|
|
2435
|
+
return bridge_cls
|
|
2436
|
+
return xl_ctp_bridge_decorator
|
|
2437
|
+
|
|
2438
|
+
class CustomTaskPane:
|
|
2439
|
+
|
|
2440
|
+
def __init__(self, *args, **kwargs):
|
|
2441
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2442
|
+
|
|
2443
|
+
def Delete(self):
|
|
2444
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2445
|
+
|
|
2446
|
+
Title = None
|
|
2447
|
+
Application = None
|
|
2448
|
+
Window = None
|
|
2449
|
+
Visible = False
|
|
2450
|
+
ContentControl = None
|
|
2451
|
+
Width = 0
|
|
2452
|
+
Height = 0
|
|
2453
|
+
DockPosition = CTPDockPositionRight
|
|
2454
|
+
DockPositionRestrict = CTPDockPositionRestrictNone
|
|
2455
|
+
|
|
2456
|
+
def create_ctp(control,
|
|
2457
|
+
title=None,
|
|
2458
|
+
width=None,
|
|
2459
|
+
height=None,
|
|
2460
|
+
position=CTPDockPositionRight,
|
|
2461
|
+
position_restrict=CTPDockPositionRestrictNone,
|
|
2462
|
+
top=None,
|
|
2463
|
+
left=None,
|
|
2464
|
+
timer_interval=0.1,
|
|
2465
|
+
bridge_cls=None): # type: (...) -> CustomTaskPane
|
|
2466
|
+
"""Creates a Custom Task Pane from a UI control object.
|
|
2467
|
+
|
|
2468
|
+
The control object can be any of the following:
|
|
2469
|
+
- tkinter.Toplevel
|
|
2470
|
+
- PyQt5.QtWidgets.QWidget
|
|
2471
|
+
- PySide2.QtWidgets.QWidget
|
|
2472
|
+
- wx.Frame
|
|
2473
|
+
|
|
2474
|
+
:param control: UI control of one of the supported types.
|
|
2475
|
+
:param title: Title of the custom task pane to be created.
|
|
2476
|
+
:param width: Initial width of the custom task pane.
|
|
2477
|
+
:param height: Initial height of the custom task pane.
|
|
2478
|
+
:param position: Where to display the custom task pane. Can be any of:
|
|
2479
|
+
- CTPDockPositionLeft
|
|
2480
|
+
- CTPDockPositionTop
|
|
2481
|
+
- CTPDockPositionRight
|
|
2482
|
+
- CTPDockPositionBottom
|
|
2483
|
+
- CTPDockPositionFloating
|
|
2484
|
+
:param position_restrict: Restriction on where the custom task pane can be positions. Can be any of:
|
|
2485
|
+
- CTPDockPositionRestrictNone
|
|
2486
|
+
- CTPDockPositionRestrictNoChange
|
|
2487
|
+
- CTPDockPositionRestrictNoHorizontal
|
|
2488
|
+
- CTPDockPositionRestrictNoVertical
|
|
2489
|
+
:param top: Initial top position of custom task pane (only used if floating).
|
|
2490
|
+
:param left: Initial left position of custom task pane (only used if floating).
|
|
2491
|
+
:param timer_interval: The interval in seconds between calls to :py:meth:`CTPBridgeBase.on_timer`.
|
|
2492
|
+
:param bridge_cls: Subclass of :py:class:`CTPBridgeBase` to use. For supported widget types this
|
|
2493
|
+
is chosen automatically.
|
|
2494
|
+
"""
|
|
2495
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2496
|
+
|
|
2497
|
+
class AtxBridgeBase(UIBridge):
|
|
2498
|
+
"""Base class of bridges between the Python UI toolkits
|
|
2499
|
+
and PyXLL's ActiveX control.
|
|
2500
|
+
"""
|
|
2501
|
+
|
|
2502
|
+
def width(self, dpi):
|
|
2503
|
+
"""Return the width of the control, in points."""
|
|
2504
|
+
return NotImplementedError()
|
|
2505
|
+
|
|
2506
|
+
def height(self, dpi):
|
|
2507
|
+
"""Return the height of the control, in points."""
|
|
2508
|
+
return NotImplementedError()
|
|
2509
|
+
|
|
2510
|
+
def xl_activex_bridge(*clsnames):
|
|
2511
|
+
"""Decorator to apply to implementations of the AtxBridgeBase class
|
|
2512
|
+
to register that class as the default bridge for a UI control.
|
|
2513
|
+
|
|
2514
|
+
For example::
|
|
2515
|
+
|
|
2516
|
+
@xl_activex_bridge("myuilib.Widget")
|
|
2517
|
+
class MyUIBridge(AtxBridgeBase):
|
|
2518
|
+
...
|
|
2519
|
+
|
|
2520
|
+
After registering a bridge class, any call to `pyxll.create_activex_control`
|
|
2521
|
+
with an object of the types specified will use the registered bridge.
|
|
2522
|
+
"""
|
|
2523
|
+
def xl_activex_bridge_decorator(bridge_cls):
|
|
2524
|
+
return bridge_cls
|
|
2525
|
+
return xl_activex_bridge_decorator
|
|
2526
|
+
|
|
2527
|
+
class ActiveXHost:
|
|
2528
|
+
"""ActiveX object returned by create_activex_control."""
|
|
2529
|
+
|
|
2530
|
+
def __init__(self):
|
|
2531
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2532
|
+
|
|
2533
|
+
def Invalidate(self):
|
|
2534
|
+
"""Requests Excel redraws the control."""
|
|
2535
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2536
|
+
|
|
2537
|
+
def create_activex_control(control,
|
|
2538
|
+
name=None,
|
|
2539
|
+
sheet=None,
|
|
2540
|
+
width=None,
|
|
2541
|
+
height=None,
|
|
2542
|
+
top=None,
|
|
2543
|
+
left=None,
|
|
2544
|
+
timer_interval=0.1,
|
|
2545
|
+
bridge_cls=None): # type: (...) -> ActiveXHost
|
|
2546
|
+
"""Creates an ActiveX control from a UI control object.
|
|
2547
|
+
|
|
2548
|
+
The control object can be any of the following:
|
|
2549
|
+
- tkinter.Toplevel
|
|
2550
|
+
- PyQt5.QtWidgets.QWidget
|
|
2551
|
+
- PySide2.QtWidgets.QWidget
|
|
2552
|
+
- wx.Frame
|
|
2553
|
+
"""
|
|
2554
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2555
|
+
|
|
2556
|
+
# Plotting
|
|
2557
|
+
|
|
2558
|
+
class PlotBridgeBase:
|
|
2559
|
+
|
|
2560
|
+
def __init__(self, figure):
|
|
2561
|
+
self.figure = figure
|
|
2562
|
+
|
|
2563
|
+
def clone(self):
|
|
2564
|
+
raise NotImplementedError()
|
|
2565
|
+
|
|
2566
|
+
def can_export(self, format):
|
|
2567
|
+
"""Return True if the figure can be exported in a specific format.
|
|
2568
|
+
Formats are svg and png.
|
|
2569
|
+
"""
|
|
2570
|
+
return False
|
|
2571
|
+
|
|
2572
|
+
def get_size_hint(self, dpi):
|
|
2573
|
+
"""Return (width, height) tuple the figure should be exported as
|
|
2574
|
+
or None. Width and height are in points (72th of an inch)."""
|
|
2575
|
+
return None
|
|
2576
|
+
|
|
2577
|
+
def export(self, width, height, dpi, format, filename, **kwargs):
|
|
2578
|
+
"""Export the figure to a file as a given size and format.
|
|
2579
|
+
|
|
2580
|
+
Can return a callable that will be called when any resources
|
|
2581
|
+
generated on export are no longer required.
|
|
2582
|
+
"""
|
|
2583
|
+
raise NotImplementedError()
|
|
2584
|
+
|
|
2585
|
+
def xl_plot_bridge(*clsnames):
|
|
2586
|
+
"""Decorator to apply to implementations of the PlotBridgeBase class
|
|
2587
|
+
to register that class as the default bridge for a plot type.
|
|
2588
|
+
|
|
2589
|
+
For example::
|
|
2590
|
+
|
|
2591
|
+
@xl_plot_bridge("myplotlib.Chart")
|
|
2592
|
+
class MyPlotLibBridge(PlotBridgeBase):
|
|
2593
|
+
...
|
|
2594
|
+
|
|
2595
|
+
After registering a plotting bridge class, any call to `pyxll.plot` with
|
|
2596
|
+
an object of the types specified will use the registered bridge.
|
|
2597
|
+
"""
|
|
2598
|
+
def xl_plot_bridge_decorator(bridge_cls):
|
|
2599
|
+
return bridge_cls
|
|
2600
|
+
return xl_plot_bridge_decorator
|
|
2601
|
+
|
|
2602
|
+
def plot(figure=None,
|
|
2603
|
+
name=None,
|
|
2604
|
+
width=None,
|
|
2605
|
+
height=None,
|
|
2606
|
+
top=None,
|
|
2607
|
+
left=None,
|
|
2608
|
+
sheet=None,
|
|
2609
|
+
allow_html=None,
|
|
2610
|
+
allow_svg=None,
|
|
2611
|
+
allow_resize=None,
|
|
2612
|
+
alt_text=None,
|
|
2613
|
+
reset=False,
|
|
2614
|
+
bridge_cls=None,
|
|
2615
|
+
**kwargs):
|
|
2616
|
+
"""Plots a figure to Excel as an embedded image.
|
|
2617
|
+
|
|
2618
|
+
The figure can be any of the following:
|
|
2619
|
+
|
|
2620
|
+
- A matplotlib Figure object
|
|
2621
|
+
|
|
2622
|
+
:param figure: Figure to plot. This can be an instance of any of the following:
|
|
2623
|
+
|
|
2624
|
+
- matplotlib.figure.Figure
|
|
2625
|
+
- plotly.graph_objects.Figure
|
|
2626
|
+
- bokeh.models.plots.Plot
|
|
2627
|
+
|
|
2628
|
+
If none, the active matplotlib.pyplot figure is used.
|
|
2629
|
+
|
|
2630
|
+
:param name: Name of Picture object in Excel. If this is None then
|
|
2631
|
+
a name will be chosen, and if called from a UDF then
|
|
2632
|
+
repeated calls with re-use the same name.
|
|
2633
|
+
|
|
2634
|
+
:param width: Width of the picture in Excel, in points.
|
|
2635
|
+
If set then height must also be set.
|
|
2636
|
+
If None the width will be taken from the figure.
|
|
2637
|
+
|
|
2638
|
+
:param height: Height of the picture in Excel, in points.
|
|
2639
|
+
If set then width must also be set.
|
|
2640
|
+
If None the height will be taken from the figure.
|
|
2641
|
+
|
|
2642
|
+
:param top: Location of the top of the plot in Excel, in points.
|
|
2643
|
+
If set then left must also be set.
|
|
2644
|
+
If None, the picture will be placed below the current or selected cell.
|
|
2645
|
+
|
|
2646
|
+
:param left: Location of the left of the plot in Excel, in points.
|
|
2647
|
+
If set then top must also be set.
|
|
2648
|
+
If None, the picture will be placed below the current or selected cell.
|
|
2649
|
+
|
|
2650
|
+
:param sheet: Name of the sheet to add the picture to. If none, the current sheet is used.
|
|
2651
|
+
|
|
2652
|
+
:param allow_html: Some figures may be rendered as HTML, if WebView2 is installed.
|
|
2653
|
+
This can be disabled by setting this option to False, or by using the
|
|
2654
|
+
config setting ``plot_allow_html = 0``.
|
|
2655
|
+
|
|
2656
|
+
:param allow_svg: Some figures may be rendered as SVG, if the version of Excel allows.
|
|
2657
|
+
This can be disabled by setting this option to False, or by using the
|
|
2658
|
+
config setting ``plot_allow_svg = 0``.
|
|
2659
|
+
|
|
2660
|
+
:param allow_resize: When allowed (default), figures will be redrawn when the shape in Excel is resized.
|
|
2661
|
+
This can be disabled by setting this option to False, or by using the
|
|
2662
|
+
config setting ``plot_allow_resize = 0``.
|
|
2663
|
+
|
|
2664
|
+
:param alt_text: Alternative (descriptive) text to use for the picture object in Excel. This can
|
|
2665
|
+
be displayed instead of the shape object if the Excel document is saved to a web page,
|
|
2666
|
+
or when the mouse hovers over the image (if supported by the browser).
|
|
2667
|
+
|
|
2668
|
+
:param reset: Reset the size and position of the image.
|
|
2669
|
+
|
|
2670
|
+
:param kwargs: Additional arguments will be called to the implementation specific
|
|
2671
|
+
method for exporting the figure to an image.
|
|
2672
|
+
"""
|
|
2673
|
+
raise Exception("Not supported when running outside of Excel")
|
|
2674
|
+
|
|
2675
|
+
# Context managers
|
|
2676
|
+
|
|
2677
|
+
class _DisableUpdatesContextManager:
|
|
2678
|
+
|
|
2679
|
+
def __init__(self, flags):
|
|
2680
|
+
self.__flags = flags
|
|
2681
|
+
|
|
2682
|
+
def __enter__(self):
|
|
2683
|
+
pass
|
|
2684
|
+
|
|
2685
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
2686
|
+
pass
|
|
2687
|
+
|
|
2688
|
+
def xl_disable(automatic_calculations=True,
|
|
2689
|
+
screen_updating=True,
|
|
2690
|
+
alerts=True,
|
|
2691
|
+
restore_selection=True,
|
|
2692
|
+
restore_active_sheet=True):
|
|
2693
|
+
"""
|
|
2694
|
+
Context manager to disable Excel while performing operations
|
|
2695
|
+
that interact with Excel.
|
|
2696
|
+
|
|
2697
|
+
Can only be used from inside an Excel macro, or from a function
|
|
2698
|
+
scheduled using pyxll.schedule_call.
|
|
2699
|
+
|
|
2700
|
+
Example::
|
|
2701
|
+
|
|
2702
|
+
@xl_macro
|
|
2703
|
+
def macro_function():
|
|
2704
|
+
with xl_disable():
|
|
2705
|
+
# do some work here that updates Excel where we do not
|
|
2706
|
+
# want Excel to automatically recalculate or update.
|
|
2707
|
+
xl = xl_app()
|
|
2708
|
+
xl.Range("A1").Value = 1
|
|
2709
|
+
|
|
2710
|
+
# After the with block, Excel reverts to its previous calculation mode.
|
|
2711
|
+
return
|
|
2712
|
+
|
|
2713
|
+
:param automatic_calculations: Disable automatic calculations until finished.
|
|
2714
|
+
:param screen_updating: Disable screen updating until finished.
|
|
2715
|
+
:param alerts: Disable alerts until finished.
|
|
2716
|
+
:param restore_selection: Restore the current selection when finished.
|
|
2717
|
+
:param restore_active_sheet: Restore the current active sheet when finished.
|
|
2718
|
+
"""
|
|
2719
|
+
flags = 0
|
|
2720
|
+
return _DisableUpdatesContextManager(flags)
|