xlio 0.1.0__py3-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.
- xlio/__init__.py +231 -0
- xlio/_book.py +381 -0
- xlio/_cells.py +487 -0
- xlio/_comments.py +144 -0
- xlio/_conditional.py +396 -0
- xlio/_drawing.py +531 -0
- xlio/_package.py +405 -0
- xlio/_patch.py +144 -0
- xlio/_print.py +339 -0
- xlio/_rich.py +165 -0
- xlio/_richvalue.py +101 -0
- xlio/_structure.py +822 -0
- xlio/_styles.py +802 -0
- xlio/_tables.py +588 -0
- xlio/_theme.py +161 -0
- xlio/_types.py +247 -0
- xlio/_workbook.py +950 -0
- xlio/_write.py +772 -0
- xlio/_zip.py +268 -0
- xlio/data/presetTableStyles.xml +18070 -0
- xlio/ns.py +76 -0
- xlio/presets.py +50 -0
- xlio/py.typed +0 -0
- xlio-0.1.0.dist-info/METADATA +61 -0
- xlio-0.1.0.dist-info/RECORD +28 -0
- xlio-0.1.0.dist-info/WHEEL +4 -0
- xlio-0.1.0.dist-info/licenses/LICENSE +21 -0
- xlio-0.1.0.dist-info/licenses/NOTICE +29 -0
xlio/__init__.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Read xlsx files as Excel reads them, and change their cells without disturbing anything else.
|
|
2
|
+
|
|
3
|
+
Standard library only. The reader checks a package before it parses anything and refuses what
|
|
4
|
+
Excel refuses; the writer copies every part it does not change byte for byte. A comment that
|
|
5
|
+
names a capture refers to values captured from Excel for Mac; ``CAPTURING.md`` lists them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from xlio import ns, presets
|
|
9
|
+
from xlio._book import CalcProperties, DefinedName
|
|
10
|
+
from xlio._cells import Cell, CellType, Formula
|
|
11
|
+
from xlio._comments import Comment, Person, ThreadedComment
|
|
12
|
+
from xlio._conditional import (
|
|
13
|
+
CfType,
|
|
14
|
+
Cfvo,
|
|
15
|
+
CfvoType,
|
|
16
|
+
ColorScale,
|
|
17
|
+
ConditionalFormat,
|
|
18
|
+
DataBar,
|
|
19
|
+
Extension,
|
|
20
|
+
IconSet,
|
|
21
|
+
Rule,
|
|
22
|
+
)
|
|
23
|
+
from xlio._drawing import (
|
|
24
|
+
Alternate,
|
|
25
|
+
Anchor,
|
|
26
|
+
AnchorKind,
|
|
27
|
+
Drawing,
|
|
28
|
+
DrawingObject,
|
|
29
|
+
Marker,
|
|
30
|
+
ObjectKind,
|
|
31
|
+
Picture,
|
|
32
|
+
Vml,
|
|
33
|
+
VmlShape,
|
|
34
|
+
)
|
|
35
|
+
from xlio._package import LimitError, PackageError, ReadLimits
|
|
36
|
+
from xlio._patch import ArrayFill, CachedValues, CellEdit, CellValue, Translate, patch
|
|
37
|
+
from xlio._print import (
|
|
38
|
+
HeaderFooter,
|
|
39
|
+
PageBreak,
|
|
40
|
+
PageMargins,
|
|
41
|
+
PageSetup,
|
|
42
|
+
PrintArea,
|
|
43
|
+
PrintOptions,
|
|
44
|
+
PrintTitles,
|
|
45
|
+
)
|
|
46
|
+
from xlio._rich import PhoneticProperties, PhoneticRun, RichString, Run
|
|
47
|
+
from xlio._richvalue import ImageValue, RichValue
|
|
48
|
+
from xlio._structure import (
|
|
49
|
+
ColumnRange,
|
|
50
|
+
Hyperlink,
|
|
51
|
+
Pane,
|
|
52
|
+
PaneName,
|
|
53
|
+
RowFormat,
|
|
54
|
+
Selection,
|
|
55
|
+
SheetFormat,
|
|
56
|
+
SheetProperties,
|
|
57
|
+
SheetView,
|
|
58
|
+
)
|
|
59
|
+
from xlio._styles import (
|
|
60
|
+
Alignment,
|
|
61
|
+
Border,
|
|
62
|
+
BorderSide,
|
|
63
|
+
BorderStyle,
|
|
64
|
+
CellFormat,
|
|
65
|
+
DifferentialFormat,
|
|
66
|
+
Fill,
|
|
67
|
+
Font,
|
|
68
|
+
GradientFill,
|
|
69
|
+
GradientStop,
|
|
70
|
+
NamedStyle,
|
|
71
|
+
PatternFill,
|
|
72
|
+
PatternType,
|
|
73
|
+
Protection,
|
|
74
|
+
Styles,
|
|
75
|
+
Underline,
|
|
76
|
+
)
|
|
77
|
+
from xlio._tables import (
|
|
78
|
+
AutoFilter,
|
|
79
|
+
ColorFilter,
|
|
80
|
+
CustomFilter,
|
|
81
|
+
DateGroup,
|
|
82
|
+
DynamicFilter,
|
|
83
|
+
FilterColumn,
|
|
84
|
+
IconFilter,
|
|
85
|
+
SortCondition,
|
|
86
|
+
SortState,
|
|
87
|
+
Table,
|
|
88
|
+
TableColumn,
|
|
89
|
+
TableStyle,
|
|
90
|
+
TableStyleElement,
|
|
91
|
+
TableStyleElementType,
|
|
92
|
+
TableStyleInfo,
|
|
93
|
+
TableStyles,
|
|
94
|
+
Top10,
|
|
95
|
+
)
|
|
96
|
+
from xlio._theme import ColorScheme, SchemeColor, SchemeFonts, Theme
|
|
97
|
+
from xlio._types import CellRef, Color, Unparsed
|
|
98
|
+
from xlio._workbook import (
|
|
99
|
+
BookView,
|
|
100
|
+
CellMetadata,
|
|
101
|
+
ErrorCode,
|
|
102
|
+
Parts,
|
|
103
|
+
Relationship,
|
|
104
|
+
Sheet,
|
|
105
|
+
SheetKind,
|
|
106
|
+
SheetState,
|
|
107
|
+
Workbook,
|
|
108
|
+
WorkbookKind,
|
|
109
|
+
WorkbookProperties,
|
|
110
|
+
check,
|
|
111
|
+
open, # noqa: A004 - xlio.open, as gzip.open and tarfile.open
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
__version__ = "0.1.0"
|
|
115
|
+
|
|
116
|
+
__all__ = [
|
|
117
|
+
"Alignment",
|
|
118
|
+
"Alternate",
|
|
119
|
+
"Anchor",
|
|
120
|
+
"AnchorKind",
|
|
121
|
+
"ArrayFill",
|
|
122
|
+
"AutoFilter",
|
|
123
|
+
"BookView",
|
|
124
|
+
"Border",
|
|
125
|
+
"BorderSide",
|
|
126
|
+
"BorderStyle",
|
|
127
|
+
"CachedValues",
|
|
128
|
+
"CalcProperties",
|
|
129
|
+
"Cell",
|
|
130
|
+
"CellEdit",
|
|
131
|
+
"CellFormat",
|
|
132
|
+
"CellMetadata",
|
|
133
|
+
"CellRef",
|
|
134
|
+
"CellType",
|
|
135
|
+
"CellValue",
|
|
136
|
+
"CfType",
|
|
137
|
+
"Cfvo",
|
|
138
|
+
"CfvoType",
|
|
139
|
+
"Color",
|
|
140
|
+
"ColorFilter",
|
|
141
|
+
"ColorScale",
|
|
142
|
+
"ColorScheme",
|
|
143
|
+
"ColumnRange",
|
|
144
|
+
"Comment",
|
|
145
|
+
"ConditionalFormat",
|
|
146
|
+
"CustomFilter",
|
|
147
|
+
"DataBar",
|
|
148
|
+
"DateGroup",
|
|
149
|
+
"DefinedName",
|
|
150
|
+
"DifferentialFormat",
|
|
151
|
+
"Drawing",
|
|
152
|
+
"DrawingObject",
|
|
153
|
+
"DynamicFilter",
|
|
154
|
+
"ErrorCode",
|
|
155
|
+
"Extension",
|
|
156
|
+
"Fill",
|
|
157
|
+
"FilterColumn",
|
|
158
|
+
"Font",
|
|
159
|
+
"Formula",
|
|
160
|
+
"GradientFill",
|
|
161
|
+
"GradientStop",
|
|
162
|
+
"HeaderFooter",
|
|
163
|
+
"Hyperlink",
|
|
164
|
+
"IconFilter",
|
|
165
|
+
"IconSet",
|
|
166
|
+
"ImageValue",
|
|
167
|
+
"LimitError",
|
|
168
|
+
"Marker",
|
|
169
|
+
"NamedStyle",
|
|
170
|
+
"ObjectKind",
|
|
171
|
+
"PackageError",
|
|
172
|
+
"PageBreak",
|
|
173
|
+
"PageMargins",
|
|
174
|
+
"PageSetup",
|
|
175
|
+
"Pane",
|
|
176
|
+
"PaneName",
|
|
177
|
+
"Parts",
|
|
178
|
+
"PatternFill",
|
|
179
|
+
"PatternType",
|
|
180
|
+
"Person",
|
|
181
|
+
"PhoneticProperties",
|
|
182
|
+
"PhoneticRun",
|
|
183
|
+
"Picture",
|
|
184
|
+
"PrintArea",
|
|
185
|
+
"PrintOptions",
|
|
186
|
+
"PrintTitles",
|
|
187
|
+
"Protection",
|
|
188
|
+
"ReadLimits",
|
|
189
|
+
"Relationship",
|
|
190
|
+
"RichString",
|
|
191
|
+
"RichValue",
|
|
192
|
+
"RowFormat",
|
|
193
|
+
"Rule",
|
|
194
|
+
"Run",
|
|
195
|
+
"SchemeColor",
|
|
196
|
+
"SchemeFonts",
|
|
197
|
+
"Selection",
|
|
198
|
+
"Sheet",
|
|
199
|
+
"SheetFormat",
|
|
200
|
+
"SheetKind",
|
|
201
|
+
"SheetProperties",
|
|
202
|
+
"SheetState",
|
|
203
|
+
"SheetView",
|
|
204
|
+
"SortCondition",
|
|
205
|
+
"SortState",
|
|
206
|
+
"Styles",
|
|
207
|
+
"Table",
|
|
208
|
+
"TableColumn",
|
|
209
|
+
"TableStyle",
|
|
210
|
+
"TableStyleElement",
|
|
211
|
+
"TableStyleElementType",
|
|
212
|
+
"TableStyleInfo",
|
|
213
|
+
"TableStyles",
|
|
214
|
+
"Theme",
|
|
215
|
+
"ThreadedComment",
|
|
216
|
+
"Top10",
|
|
217
|
+
"Translate",
|
|
218
|
+
"Underline",
|
|
219
|
+
"Unparsed",
|
|
220
|
+
"Vml",
|
|
221
|
+
"VmlShape",
|
|
222
|
+
"Workbook",
|
|
223
|
+
"WorkbookKind",
|
|
224
|
+
"WorkbookProperties",
|
|
225
|
+
"__version__",
|
|
226
|
+
"check",
|
|
227
|
+
"ns",
|
|
228
|
+
"open",
|
|
229
|
+
"patch",
|
|
230
|
+
"presets",
|
|
231
|
+
]
|
xlio/_book.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""The workbook: sheets, defined names, the date system, calculation settings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import posixpath
|
|
7
|
+
import xml.parsers.expat
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
from typing import Any, BinaryIO
|
|
12
|
+
|
|
13
|
+
from xlio._cells import Cell, read_cells, read_shared_strings
|
|
14
|
+
from xlio._package import Package, PackageError, ReadLimits
|
|
15
|
+
from xlio._rich import RichString, read_rich_strings
|
|
16
|
+
from xlio._types import bounded_int
|
|
17
|
+
|
|
18
|
+
__all__ = ["Book", "CalcProperties", "DefinedName", "SheetInfo"]
|
|
19
|
+
|
|
20
|
+
_MAINS = (
|
|
21
|
+
"{http://schemas.openxmlformats.org/spreadsheetml/2006/main}",
|
|
22
|
+
"{http://purl.oclc.org/ooxml/spreadsheetml/main}",
|
|
23
|
+
)
|
|
24
|
+
_RELS = (
|
|
25
|
+
"{http://schemas.openxmlformats.org/officeDocument/2006/relationships}",
|
|
26
|
+
"{http://purl.oclc.org/ooxml/officeDocument/relationships}",
|
|
27
|
+
)
|
|
28
|
+
_TRUE = ("1", "true")
|
|
29
|
+
# Rich-value error types and the error Excel shows for each (capture errors). Another type is
|
|
30
|
+
# shown as the #VALUE! the cell caches; 7 and 17 are refused.
|
|
31
|
+
_RICH_ERRORS = {
|
|
32
|
+
"3": "#REF!", "4": "#NAME?", "6": "#N/A", "8": "#SPILL!", "9": "#CONNECT!",
|
|
33
|
+
"10": "#BLOCKED!", "11": "#UNKNOWN!", "12": "#FIELD!", "13": "#CALC!",
|
|
34
|
+
"15": "#BUSY!", "18": "#UNKNOWN!", "19": "#TIMEOUT!",
|
|
35
|
+
} # fmt: skip
|
|
36
|
+
_REFUSED_ERROR_TYPES = frozenset({"7", "17"})
|
|
37
|
+
# errorType 14: Excel saves the cell as the number 0 (its rich value dropped) and a formula
|
|
38
|
+
# referring to it caches 0, so it is read as 0; at load-time calculation ERROR.TYPE gave 15 and
|
|
39
|
+
# VALUETOTEXT "#CALC!", so what Excel shows in the cell itself is still to be captured.
|
|
40
|
+
_RICH_NUMBERS = {"14": 0.0}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class SheetInfo:
|
|
45
|
+
"""A sheet: name, part, ``visible``/``hidden``/``veryHidden``, and its kind.
|
|
46
|
+
|
|
47
|
+
``kind`` is the last segment of the relationship type: ``worksheet``, ``chartsheet``,
|
|
48
|
+
``dialogsheet`` or ``xlMacrosheet``; only worksheets have cells to read.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
part: str
|
|
53
|
+
state: str
|
|
54
|
+
kind: str
|
|
55
|
+
position: int = 0
|
|
56
|
+
"""Its place in ``<sheets>`` as written, 0-based: what ``localSheetId`` and ``activeTab``
|
|
57
|
+
count, a sheet without a part included."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class DefinedName:
|
|
62
|
+
"""A defined name: its text (a formula, file form), scope, hidden.
|
|
63
|
+
|
|
64
|
+
``sheet`` is ``localSheetId`` as written: the sheet's place in ``<sheets>``, a sheet without a
|
|
65
|
+
part counted (``Sheet.position``), or ``None`` for a name of the workbook.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
name: str
|
|
69
|
+
text: str
|
|
70
|
+
sheet: int | None
|
|
71
|
+
hidden: bool
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class CalcProperties:
|
|
76
|
+
"""``<calcPr>`` as written; ``None`` where the file leaves an attribute out."""
|
|
77
|
+
|
|
78
|
+
calc_id: int | None = None
|
|
79
|
+
full_calc_on_load: bool = False
|
|
80
|
+
calc_mode: str | None = None
|
|
81
|
+
iterate: bool = False
|
|
82
|
+
iterate_count: int | None = None
|
|
83
|
+
iterate_delta: float | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _find(element: object, local: str) -> list[object]:
|
|
87
|
+
return [e for ns in _MAINS for e in element.iter(ns + local)] # type: ignore[attr-defined]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _local(element: object, local: str) -> list[Any]:
|
|
91
|
+
"""Descendants with this local name, in any namespace."""
|
|
92
|
+
return [
|
|
93
|
+
e
|
|
94
|
+
for e in element.iter() # type: ignore[attr-defined]
|
|
95
|
+
if isinstance(e.tag, str) and e.tag.rpartition("}")[2] == local
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _attr(element: object, local: str) -> str | None:
|
|
100
|
+
for ns in _RELS:
|
|
101
|
+
value = element.get(ns + local) # type: ignore[attr-defined]
|
|
102
|
+
if value is not None:
|
|
103
|
+
return str(value)
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Book:
|
|
108
|
+
"""An xlsx workbook opened for reading. Use as a context manager, or ``close`` it."""
|
|
109
|
+
|
|
110
|
+
def __init__(
|
|
111
|
+
self,
|
|
112
|
+
source: str | os.PathLike[str] | BinaryIO,
|
|
113
|
+
limits: ReadLimits | None = None,
|
|
114
|
+
) -> None:
|
|
115
|
+
self._package = Package(source, limits or ReadLimits())
|
|
116
|
+
try:
|
|
117
|
+
self._load()
|
|
118
|
+
except BaseException:
|
|
119
|
+
self._package.close()
|
|
120
|
+
raise
|
|
121
|
+
self._strings: list[str] | None = None
|
|
122
|
+
self._rich: list[RichString] | None = None
|
|
123
|
+
|
|
124
|
+
def __enter__(self) -> Book:
|
|
125
|
+
return self
|
|
126
|
+
|
|
127
|
+
def __exit__(
|
|
128
|
+
self,
|
|
129
|
+
exc_type: type[BaseException] | None,
|
|
130
|
+
exc: BaseException | None,
|
|
131
|
+
traceback: TracebackType | None,
|
|
132
|
+
) -> None:
|
|
133
|
+
self.close()
|
|
134
|
+
|
|
135
|
+
def close(self) -> None:
|
|
136
|
+
"""Close the file."""
|
|
137
|
+
self._package.close()
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def package(self) -> Package:
|
|
141
|
+
"""The package, for the writer."""
|
|
142
|
+
return self._package
|
|
143
|
+
|
|
144
|
+
def _load(self) -> None:
|
|
145
|
+
package = self._package
|
|
146
|
+
root_rels = package.relationships("")
|
|
147
|
+
workbook = next(
|
|
148
|
+
(
|
|
149
|
+
t
|
|
150
|
+
for typ, t, ext in root_rels.values()
|
|
151
|
+
if typ.endswith("/officeDocument") and not ext
|
|
152
|
+
),
|
|
153
|
+
None,
|
|
154
|
+
)
|
|
155
|
+
if workbook is None or workbook not in package.names:
|
|
156
|
+
raise PackageError("the package has no workbook part")
|
|
157
|
+
self.workbook_part = workbook
|
|
158
|
+
rels = package.relationships(workbook)
|
|
159
|
+
root = package.xml(workbook)
|
|
160
|
+
self.root = root
|
|
161
|
+
"""The workbook part's element tree."""
|
|
162
|
+
self.sheets: list[SheetInfo] = []
|
|
163
|
+
for position, sheet in enumerate(_find(root, "sheet")):
|
|
164
|
+
rel = rels.get(_attr(sheet, "id") or "")
|
|
165
|
+
if rel is None:
|
|
166
|
+
continue
|
|
167
|
+
kind = rel[0].rsplit("/", 1)[-1]
|
|
168
|
+
self.sheets.append(
|
|
169
|
+
SheetInfo(
|
|
170
|
+
sheet.get("name", ""), # type: ignore[attr-defined]
|
|
171
|
+
rel[1],
|
|
172
|
+
sheet.get("state", "visible"), # type: ignore[attr-defined]
|
|
173
|
+
kind,
|
|
174
|
+
position,
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
views = _find(root, "workbookView")
|
|
178
|
+
tab = views[0].get("activeTab", "0") if views else "0" # type: ignore[attr-defined]
|
|
179
|
+
self.active_tab = bounded_int(tab) if tab.isdigit() and tab.isascii() else 0
|
|
180
|
+
"""The sheet the workbook opens on (``workbookView activeTab``), 0-based."""
|
|
181
|
+
props = _find(root, "workbookPr")
|
|
182
|
+
self.date1904 = bool(props) and props[0].get("date1904", "0") in _TRUE # type: ignore[attr-defined]
|
|
183
|
+
calc = _find(root, "calcPr")
|
|
184
|
+
self.calc = _calc(calc[0]) if calc else CalcProperties()
|
|
185
|
+
self.defined_names: list[DefinedName] = []
|
|
186
|
+
for dn in _find(root, "definedName"):
|
|
187
|
+
local = dn.get("localSheetId") # type: ignore[attr-defined]
|
|
188
|
+
self.defined_names.append(
|
|
189
|
+
DefinedName(
|
|
190
|
+
dn.get("name", ""), # type: ignore[attr-defined]
|
|
191
|
+
dn.text or "", # type: ignore[attr-defined]
|
|
192
|
+
_integer(local, "localSheetId") if local is not None else None,
|
|
193
|
+
dn.get("hidden", "0") in _TRUE, # type: ignore[attr-defined]
|
|
194
|
+
)
|
|
195
|
+
)
|
|
196
|
+
self._strings_part = next(
|
|
197
|
+
(t for typ, t, ext in rels.values() if typ.endswith("/sharedStrings") and not ext),
|
|
198
|
+
None,
|
|
199
|
+
)
|
|
200
|
+
self.dynamic_cm: frozenset[int] = frozenset()
|
|
201
|
+
"""The ``cm`` values that mark a dynamic-array formula (metadata type ``XLDAPR``)."""
|
|
202
|
+
self.metadata_counts = (0, 0) # the cellMetadata and valueMetadata entries
|
|
203
|
+
self.value_rich: dict[int, int] = {} # vm -> the rich value's index (XLRICHVALUE)
|
|
204
|
+
self.value_errors: dict[int, str | float] = {}
|
|
205
|
+
"""``vm`` value -> what a rich value stands for, for a cell that caches ``#VALUE!``: an
|
|
206
|
+
error (``#SPILL!``), or a number (errorType 14)."""
|
|
207
|
+
meta = next(
|
|
208
|
+
(t for typ, t, ext in rels.values() if typ.endswith("/sheetMetadata") and not ext),
|
|
209
|
+
None,
|
|
210
|
+
)
|
|
211
|
+
if meta is not None and meta in package.names:
|
|
212
|
+
self._metadata(meta, rels)
|
|
213
|
+
self.external_links = [
|
|
214
|
+
t for typ, t, ext in rels.values() if typ.endswith("/externalLink") and not ext
|
|
215
|
+
]
|
|
216
|
+
|
|
217
|
+
def _metadata(self, part: str, rels: dict[str, tuple[str, str, bool]]) -> None:
|
|
218
|
+
"""The dynamic-array and rich-value metadata.
|
|
219
|
+
|
|
220
|
+
As Excel writes it (captured by xlrecalc: https://github.com/sheetmill/xlrecalc/blob/main/tests/captures/arrays.tsv).
|
|
221
|
+
"""
|
|
222
|
+
root = self._package.xml(part)
|
|
223
|
+
types = [t.get("name", "") for t in _local(root, "metadataType")]
|
|
224
|
+
future: dict[str, list[object]] = {}
|
|
225
|
+
for fm in _local(root, "futureMetadata"):
|
|
226
|
+
future[fm.get("name", "")] = list(_local(fm, "bk"))
|
|
227
|
+
|
|
228
|
+
def entries(block: str) -> list[tuple[str, int]]:
|
|
229
|
+
out = []
|
|
230
|
+
for container in _local(root, block):
|
|
231
|
+
for bk in _local(container, "bk"):
|
|
232
|
+
rc = next(iter(_local(bk, "rc")), None)
|
|
233
|
+
if rc is None:
|
|
234
|
+
out.append(("", 0))
|
|
235
|
+
continue
|
|
236
|
+
t = _int_or(rc.get("t", "0"), 0)
|
|
237
|
+
v = _int_or(rc.get("v", "0"), -1)
|
|
238
|
+
out.append((types[t - 1] if 0 < t <= len(types) else "", v))
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
cell_entries, value_entries = entries("cellMetadata"), entries("valueMetadata")
|
|
242
|
+
self.metadata_counts = (len(cell_entries), len(value_entries))
|
|
243
|
+
dynamic = set()
|
|
244
|
+
for k, (name, v) in enumerate(cell_entries, 1):
|
|
245
|
+
blocks = future.get(name, [])
|
|
246
|
+
if name == "XLDAPR" and 0 <= v < len(blocks):
|
|
247
|
+
props = next(iter(_local(blocks[v], "dynamicArrayProperties")), None)
|
|
248
|
+
if props is not None and props.get("fDynamic", "0") in _TRUE:
|
|
249
|
+
dynamic.add(k)
|
|
250
|
+
self.dynamic_cm = frozenset(dynamic)
|
|
251
|
+
values = self._rich_errors(rels)
|
|
252
|
+
for k, (name, v) in enumerate(value_entries, 1):
|
|
253
|
+
blocks = future.get(name, [])
|
|
254
|
+
if name == "XLRICHVALUE" and 0 <= v < len(blocks):
|
|
255
|
+
rvb = next(iter(_local(blocks[v], "rvb")), None)
|
|
256
|
+
if rvb is not None:
|
|
257
|
+
index = _int_or(rvb.get("i", "-1"), -1)
|
|
258
|
+
if index >= 0:
|
|
259
|
+
self.value_rich[k] = index
|
|
260
|
+
error = values.get(index)
|
|
261
|
+
if error is not None:
|
|
262
|
+
self.value_errors[k] = error
|
|
263
|
+
|
|
264
|
+
def _rich_errors(self, rels: dict[str, tuple[str, str, bool]]) -> dict[int, str | float]:
|
|
265
|
+
"""Rich value index -> the error Excel shows for it, for the error types captured."""
|
|
266
|
+
parts = {typ.rsplit("/", 1)[-1].lower(): t for typ, t, ext in rels.values() if not ext}
|
|
267
|
+
values_part = parts.get("rdrichvalue")
|
|
268
|
+
structures_part = parts.get("rdrichvaluestructure")
|
|
269
|
+
if values_part not in self._package.names or structures_part not in self._package.names:
|
|
270
|
+
return {}
|
|
271
|
+
assert values_part is not None
|
|
272
|
+
assert structures_part is not None
|
|
273
|
+
structures = []
|
|
274
|
+
for st in _local(self._package.xml(structures_part), "s"):
|
|
275
|
+
keys = [k.get("n", "") for k in _local(st, "k")]
|
|
276
|
+
structures.append((st.get("t", ""), keys))
|
|
277
|
+
out = {}
|
|
278
|
+
for i, rv in enumerate(_local(self._package.xml(values_part), "rv")):
|
|
279
|
+
s = _int_or(rv.get("s", "-1"), -1)
|
|
280
|
+
if not 0 <= s < len(structures) or structures[s][0] != "_error":
|
|
281
|
+
continue
|
|
282
|
+
fields = dict(zip(structures[s][1], (v.text for v in _local(rv, "v")), strict=False))
|
|
283
|
+
error_type = (fields.get("errorType") or "").strip()
|
|
284
|
+
if error_type in _REFUSED_ERROR_TYPES:
|
|
285
|
+
raise PackageError(f"{values_part}: a rich value of errorType {error_type}, "
|
|
286
|
+
"which Excel refuses") # fmt: skip
|
|
287
|
+
code: str | float | None = _RICH_ERRORS.get(error_type, _RICH_NUMBERS.get(error_type))
|
|
288
|
+
if code is not None:
|
|
289
|
+
out[i] = code
|
|
290
|
+
return out
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def shared_strings(self) -> list[str]:
|
|
294
|
+
"""The shared string table, read once."""
|
|
295
|
+
if self._strings is None:
|
|
296
|
+
part = self._strings_part
|
|
297
|
+
if part is None or part not in self._package.names:
|
|
298
|
+
self._strings = []
|
|
299
|
+
else:
|
|
300
|
+
with self._package.part(part) as f:
|
|
301
|
+
try:
|
|
302
|
+
self._strings = read_shared_strings(f)
|
|
303
|
+
except xml.parsers.expat.ExpatError as exc:
|
|
304
|
+
raise PackageError(f"{part}: {exc}") from exc
|
|
305
|
+
return self._strings
|
|
306
|
+
|
|
307
|
+
@property
|
|
308
|
+
def rich_strings(self) -> list[RichString]:
|
|
309
|
+
"""The shared string table with runs and phonetic guides, read once."""
|
|
310
|
+
if self._rich is None:
|
|
311
|
+
part = self._strings_part
|
|
312
|
+
if part is None or part not in self._package.names:
|
|
313
|
+
self._rich = []
|
|
314
|
+
else:
|
|
315
|
+
with self._package.part(part) as f:
|
|
316
|
+
self._rich = read_rich_strings(f, part)
|
|
317
|
+
return self._rich
|
|
318
|
+
|
|
319
|
+
def sheet(self, name: str) -> SheetInfo:
|
|
320
|
+
"""The sheet with this name (Excel compares sheet names without case)."""
|
|
321
|
+
folded = name.casefold()
|
|
322
|
+
for sheet in self.sheets:
|
|
323
|
+
if sheet.name.casefold() == folded:
|
|
324
|
+
return sheet
|
|
325
|
+
raise KeyError(f"no sheet named {name!r}")
|
|
326
|
+
|
|
327
|
+
def cells(
|
|
328
|
+
self,
|
|
329
|
+
sheet: str | SheetInfo,
|
|
330
|
+
rich_strings: list[RichString] | None = None,
|
|
331
|
+
**options: Any,
|
|
332
|
+
) -> Iterator[Cell]:
|
|
333
|
+
"""The cells of a worksheet, streamed in file order; ``options`` go to ``read_cells``."""
|
|
334
|
+
info = sheet if isinstance(sheet, SheetInfo) else self.sheet(sheet)
|
|
335
|
+
if info.kind != "worksheet":
|
|
336
|
+
raise ValueError(f"{info.name!r} is a {info.kind}, not a worksheet")
|
|
337
|
+
strings = self.shared_strings
|
|
338
|
+
with self._package.part(info.part) as f:
|
|
339
|
+
try:
|
|
340
|
+
yield from read_cells(f, strings, rich_strings, **options)
|
|
341
|
+
except xml.parsers.expat.ExpatError as exc:
|
|
342
|
+
raise PackageError(f"{info.part}: {exc}") from exc
|
|
343
|
+
|
|
344
|
+
def part_name(self, relative: str) -> str:
|
|
345
|
+
"""A part name relative to the workbook part's folder."""
|
|
346
|
+
return posixpath.normpath(posixpath.join(posixpath.dirname(self.workbook_part), relative))
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _int_or(text: str, default: int) -> int:
|
|
350
|
+
"""An integer attribute the reader can do without: its default when it is not one."""
|
|
351
|
+
try:
|
|
352
|
+
return int(text)
|
|
353
|
+
except ValueError:
|
|
354
|
+
return default
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _integer(text: str, what: str) -> int:
|
|
358
|
+
try:
|
|
359
|
+
return int(text)
|
|
360
|
+
except ValueError:
|
|
361
|
+
raise PackageError(f"{what}: not an integer: {text[:40]!r}") from None
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _calc(element: object) -> CalcProperties:
|
|
365
|
+
"""The calculation settings; a number that is not one is taken as absent (none computes)."""
|
|
366
|
+
get = element.get # type: ignore[attr-defined]
|
|
367
|
+
calc_id = get("calcId")
|
|
368
|
+
count = get("iterateCount")
|
|
369
|
+
delta = get("iterateDelta")
|
|
370
|
+
try:
|
|
371
|
+
iterate_delta = float(delta) if delta is not None else None
|
|
372
|
+
except ValueError:
|
|
373
|
+
iterate_delta = None
|
|
374
|
+
return CalcProperties(
|
|
375
|
+
calc_id=_int_or(calc_id, -1) if calc_id is not None else None,
|
|
376
|
+
full_calc_on_load=get("fullCalcOnLoad", "0") in _TRUE,
|
|
377
|
+
calc_mode=get("calcMode"),
|
|
378
|
+
iterate=get("iterate", "0") in _TRUE,
|
|
379
|
+
iterate_count=_int_or(count, -1) if count is not None else None,
|
|
380
|
+
iterate_delta=iterate_delta,
|
|
381
|
+
)
|