pycraftbox-excel 4.0.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.
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Excel column formatting helpers for :mod:`pycraftbox.excel`.
|
|
2
|
+
|
|
3
|
+
This module hosts the :class:`ExcelCurrency` enum and the
|
|
4
|
+
:class:`ColumnFormatter` factory used to apply number, currency, date, and
|
|
5
|
+
text-wrap formats when writing DataFrames to Excel workbooks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
from xlsxwriter.workbook import Workbook
|
|
16
|
+
from xlsxwriter.worksheet import Worksheet
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ExcelCurrency(Enum):
|
|
20
|
+
"""Supported currency codes for Excel number formatting."""
|
|
21
|
+
|
|
22
|
+
EUR = "#,##0.00 [$€-407]"
|
|
23
|
+
USD = r"#,##0.00 [$\$-409]"
|
|
24
|
+
GBP = "#,##0.00 [$£-809]"
|
|
25
|
+
CHF = "#,##0.00 [$CHF-407]"
|
|
26
|
+
JPY = "#,##0 [$¥-411]"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclasses.dataclass
|
|
30
|
+
class ColumnFormatter:
|
|
31
|
+
"""Formatter specification for one or more Excel columns.
|
|
32
|
+
|
|
33
|
+
Acts as a factory for common Excel column formatters via its class methods.
|
|
34
|
+
|
|
35
|
+
Attributes:
|
|
36
|
+
columns: List of columns to format. Each entry is either a 0-based integer
|
|
37
|
+
index or a column name string. Names are resolved to indices at write
|
|
38
|
+
time via :meth:`resolved_indices`.
|
|
39
|
+
formatter: Callable that receives ``(workbook, worksheet, col_num)`` and
|
|
40
|
+
applies formatting to the specified column.
|
|
41
|
+
|
|
42
|
+
Example::
|
|
43
|
+
|
|
44
|
+
formatters = [
|
|
45
|
+
ColumnFormatter.currency(columns=["profit", "loss"], currency=ExcelCurrency.EUR),
|
|
46
|
+
ColumnFormatter.date(columns=["date"], date_format="dd/mm/yyyy"),
|
|
47
|
+
ColumnFormatter.text_wrap(columns=["description"]),
|
|
48
|
+
]
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
columns: list[int | str]
|
|
52
|
+
formatter: Callable[[Workbook, Worksheet, int], None]
|
|
53
|
+
|
|
54
|
+
def resolved_indices(self, df_columns: pd.Index) -> list[int]:
|
|
55
|
+
"""Resolve column names and indices to a list of 0-based integer indices.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
df_columns: The :attr:`~pandas.DataFrame.columns` index of the target
|
|
59
|
+
DataFrame, used to look up column names.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
A list of 0-based integer column positions.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
KeyError: If a string column name is not found in *df_columns*.
|
|
66
|
+
"""
|
|
67
|
+
result: list[int] = []
|
|
68
|
+
for col in self.columns:
|
|
69
|
+
if isinstance(col, str):
|
|
70
|
+
loc = df_columns.get_loc(col)
|
|
71
|
+
if not isinstance(loc, int):
|
|
72
|
+
# get_loc can return a slice/array for duplicate labels
|
|
73
|
+
raise KeyError(
|
|
74
|
+
f"Column name '{col}' matches multiple columns or is ambiguous."
|
|
75
|
+
)
|
|
76
|
+
result.append(loc)
|
|
77
|
+
else:
|
|
78
|
+
result.append(col)
|
|
79
|
+
return result
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def currency(
|
|
83
|
+
cls,
|
|
84
|
+
columns: list[int | str],
|
|
85
|
+
currency: ExcelCurrency = ExcelCurrency.EUR,
|
|
86
|
+
) -> ColumnFormatter:
|
|
87
|
+
"""Return a :class:`ColumnFormatter` that applies a currency number format.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
columns: Columns to format — each entry is either a 0-based integer
|
|
91
|
+
index or a column name string.
|
|
92
|
+
currency: The currency to use. Defaults to :attr:`ExcelCurrency.EUR`.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
A :class:`ColumnFormatter` instance ready for use with
|
|
96
|
+
:meth:`ExcelFileMapper.add_excel_sheet`.
|
|
97
|
+
"""
|
|
98
|
+
num_format = currency.value
|
|
99
|
+
|
|
100
|
+
def _fmt(workbook: Workbook, worksheet: Worksheet, col_num: int) -> None:
|
|
101
|
+
fmt = workbook.add_format({"num_format": num_format})
|
|
102
|
+
worksheet.set_column(col_num, col_num, cell_format=fmt)
|
|
103
|
+
|
|
104
|
+
return cls(columns=columns, formatter=_fmt)
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def number(
|
|
108
|
+
cls,
|
|
109
|
+
columns: list[int | str],
|
|
110
|
+
decimals: int = 2,
|
|
111
|
+
) -> ColumnFormatter:
|
|
112
|
+
"""Return a :class:`ColumnFormatter` that applies a number format with specified decimals.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
columns: Columns to format — each entry is either a 0-based integer
|
|
116
|
+
index or a column name string.
|
|
117
|
+
decimals: Number of decimal places to display. Defaults to 2.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
A :class:`ColumnFormatter` instance ready for use with
|
|
121
|
+
:meth:`ExcelFileMapper.add_excel_sheet`.
|
|
122
|
+
"""
|
|
123
|
+
# Build Excel number format: 0.00 for 2 decimals, 0.000 for 3 decimals, etc.
|
|
124
|
+
if decimals == 0:
|
|
125
|
+
num_format = "0"
|
|
126
|
+
else:
|
|
127
|
+
num_format = "0." + "0" * decimals
|
|
128
|
+
|
|
129
|
+
def _fmt(workbook: Workbook, worksheet: Worksheet, col_num: int) -> None:
|
|
130
|
+
fmt = workbook.add_format({"num_format": num_format})
|
|
131
|
+
worksheet.set_column(col_num, col_num, cell_format=fmt)
|
|
132
|
+
|
|
133
|
+
return cls(columns=columns, formatter=_fmt)
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def date(
|
|
137
|
+
cls,
|
|
138
|
+
columns: list[int | str],
|
|
139
|
+
date_format: str = "dd/mm/yyyy",
|
|
140
|
+
) -> ColumnFormatter:
|
|
141
|
+
"""Return a :class:`ColumnFormatter` that applies a date number format.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
columns: Columns to format — each entry is either a 0-based integer
|
|
145
|
+
index or a column name string.
|
|
146
|
+
date_format: Excel date format string. Defaults to ``"dd/mm/yyyy"``.
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
A :class:`ColumnFormatter` instance ready for use with
|
|
150
|
+
:meth:`ExcelFileMapper.add_excel_sheet`.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
def _fmt(workbook: Workbook, worksheet: Worksheet, col_num: int) -> None:
|
|
154
|
+
fmt = workbook.add_format({"num_format": date_format})
|
|
155
|
+
worksheet.set_column(col_num, col_num, cell_format=fmt)
|
|
156
|
+
|
|
157
|
+
return cls(columns=columns, formatter=_fmt)
|
|
158
|
+
|
|
159
|
+
@classmethod
|
|
160
|
+
def text_wrap(cls, columns: list[int | str]) -> ColumnFormatter:
|
|
161
|
+
"""Return a :class:`ColumnFormatter` that enables text wrapping.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
columns: Columns to format — each entry is either a 0-based integer
|
|
165
|
+
index or a column name string.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
A :class:`ColumnFormatter` instance ready for use with
|
|
169
|
+
:meth:`ExcelFileMapper.add_excel_sheet`.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def _fmt(workbook: Workbook, worksheet: Worksheet, col_num: int) -> None:
|
|
173
|
+
fmt = workbook.add_format()
|
|
174
|
+
fmt.set_text_wrap()
|
|
175
|
+
worksheet.set_column(col_num, col_num, cell_format=fmt)
|
|
176
|
+
|
|
177
|
+
return cls(columns=columns, formatter=_fmt)
|
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""Excel workbook mapping utilities built on pycraftbox-dataframe."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from io import BytesIO
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, BinaryIO, Union, cast
|
|
12
|
+
from xml.etree import ElementTree
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
from xlsxwriter.workbook import Workbook
|
|
16
|
+
from xlsxwriter.worksheet import Worksheet
|
|
17
|
+
|
|
18
|
+
from pycraftbox.dataframe import ColMapping, CompiledMapping, DFFileMapper
|
|
19
|
+
|
|
20
|
+
from .formatters import ColumnFormatter
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExcelFileMapper(DFFileMapper):
|
|
24
|
+
"""Read and write Excel workbooks using a declarative dataframe mapping."""
|
|
25
|
+
|
|
26
|
+
_logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
_SPREADSHEETML_NAMESPACE = "urn:schemas-microsoft-com:office:spreadsheet"
|
|
29
|
+
_INVALID_XML_CONTROLS = re.compile(rb"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
|
30
|
+
_BARE_XML_AMPERSANDS = re.compile(
|
|
31
|
+
rb"&(?!#\d+;|#x[0-9A-Fa-f]+;|[A-Za-z_:][A-Za-z0-9_.:-]*;)"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def read_excel_sheet(
|
|
36
|
+
cls,
|
|
37
|
+
input: Union[str, bytes, bytearray, BinaryIO, os.PathLike],
|
|
38
|
+
sheet_name: str,
|
|
39
|
+
*,
|
|
40
|
+
cpl_mapping: CompiledMapping | None = None,
|
|
41
|
+
read_excel_args: Mapping[str, Any] = {},
|
|
42
|
+
) -> pd.DataFrame:
|
|
43
|
+
"""Read a single sheet from an Excel workbook into a DataFrame.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
input: Path, URL, bytes, or binary file-like object. In addition
|
|
47
|
+
to formats accepted by :func:`pandas.read_excel`, XML-based
|
|
48
|
+
SpreadsheetML 2003 workbooks are detected and converted in
|
|
49
|
+
memory. Any valid string path is acceptable, including URLs
|
|
50
|
+
with schemes such as ``http``, ``ftp``, ``s3``, and ``file``.
|
|
51
|
+
A local file URL example is
|
|
52
|
+
``file://localhost/path/to/table.xlsx``.
|
|
53
|
+
sheet_name: Name of the worksheet to read.
|
|
54
|
+
cpl_mapping: A :class:`CompiledMapping` that declares which columns to
|
|
55
|
+
read, how to transform them, and which to exclude. Defaults to
|
|
56
|
+
``None``, which reads all columns as-is (equivalent to
|
|
57
|
+
``CompiledMapping(ColMapping())``).
|
|
58
|
+
read_excel_args: Additional keyword arguments forwarded to
|
|
59
|
+
:func:`pandas.read_excel`. The ``"sheet_name"`` key is
|
|
60
|
+
managed by this method and will be overwritten.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
A :class:`~pandas.DataFrame` shaped and typed according to the
|
|
64
|
+
compiled plan.
|
|
65
|
+
"""
|
|
66
|
+
if isinstance(input, (bytes, bytearray)):
|
|
67
|
+
content = bytes(input)
|
|
68
|
+
input = (
|
|
69
|
+
cls._spreadsheetml_to_xlsx(content, sheet_name)
|
|
70
|
+
if cls._is_spreadsheetml(content)
|
|
71
|
+
else BytesIO(content)
|
|
72
|
+
)
|
|
73
|
+
elif isinstance(input, (str, os.PathLike)):
|
|
74
|
+
input = Path(input).expanduser()
|
|
75
|
+
else:
|
|
76
|
+
position = input.tell()
|
|
77
|
+
prefix = input.read(4096)
|
|
78
|
+
input.seek(position)
|
|
79
|
+
if cls._is_spreadsheetml(prefix):
|
|
80
|
+
content = input.read()
|
|
81
|
+
input.seek(position)
|
|
82
|
+
input = cls._spreadsheetml_to_xlsx(content, sheet_name)
|
|
83
|
+
|
|
84
|
+
effective_compiled = (
|
|
85
|
+
cpl_mapping if cpl_mapping is not None else CompiledMapping(ColMapping())
|
|
86
|
+
)
|
|
87
|
+
excel_args = dict(read_excel_args) | {"sheet_name": sheet_name}
|
|
88
|
+
res_df = cls.read_to_df(
|
|
89
|
+
pd.read_excel,
|
|
90
|
+
input=input,
|
|
91
|
+
cpl_mapping=effective_compiled,
|
|
92
|
+
read_args=excel_args,
|
|
93
|
+
)
|
|
94
|
+
return res_df
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def _is_spreadsheetml(cls, content: bytes) -> bool:
|
|
98
|
+
"""Return whether bytes contain a SpreadsheetML 2003 workbook header."""
|
|
99
|
+
return cls._SPREADSHEETML_NAMESPACE.encode() in content[:4096]
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def _spreadsheetml_to_xlsx(cls, content: bytes, sheet_name: str) -> BytesIO:
|
|
103
|
+
"""Convert one SpreadsheetML 2003 worksheet to an in-memory XLSX workbook."""
|
|
104
|
+
sanitized = cls._INVALID_XML_CONTROLS.sub(b"", content)
|
|
105
|
+
sanitized = cls._BARE_XML_AMPERSANDS.sub(b"&", sanitized)
|
|
106
|
+
root = ElementTree.fromstring(sanitized)
|
|
107
|
+
|
|
108
|
+
namespace = cls._SPREADSHEETML_NAMESPACE
|
|
109
|
+
name_attribute = f"{{{namespace}}}Name"
|
|
110
|
+
worksheets = root.findall(f".//{{{namespace}}}Worksheet")
|
|
111
|
+
worksheet = next(
|
|
112
|
+
(item for item in worksheets if item.get(name_attribute) == sheet_name),
|
|
113
|
+
None,
|
|
114
|
+
)
|
|
115
|
+
if worksheet is None:
|
|
116
|
+
available = [item.get(name_attribute, "") for item in worksheets]
|
|
117
|
+
raise ValueError(
|
|
118
|
+
f"Worksheet '{sheet_name}' was not found. Available sheets: {available}"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
rows: list[list[Any]] = []
|
|
122
|
+
index_attribute = f"{{{namespace}}}Index"
|
|
123
|
+
merge_attribute = f"{{{namespace}}}MergeAcross"
|
|
124
|
+
type_attribute = f"{{{namespace}}}Type"
|
|
125
|
+
for row in worksheet.findall(f".//{{{namespace}}}Row"):
|
|
126
|
+
values: list[Any] = []
|
|
127
|
+
for cell in row.findall(f"{{{namespace}}}Cell"):
|
|
128
|
+
target_index = int(cell.get(index_attribute, len(values) + 1))
|
|
129
|
+
values.extend([None] * max(target_index - len(values) - 1, 0))
|
|
130
|
+
|
|
131
|
+
data = cell.find(f"{{{namespace}}}Data")
|
|
132
|
+
value: Any = None if data is None else "".join(data.itertext())
|
|
133
|
+
data_type = None if data is None else data.get(type_attribute)
|
|
134
|
+
if value is not None and data_type == "Number":
|
|
135
|
+
number = float(value)
|
|
136
|
+
value = int(number) if number.is_integer() else number
|
|
137
|
+
elif value is not None and data_type == "Boolean":
|
|
138
|
+
value = value == "1"
|
|
139
|
+
elif value is not None and data_type == "DateTime":
|
|
140
|
+
value = pd.Timestamp(value)
|
|
141
|
+
values.append(value)
|
|
142
|
+
values.extend([None] * int(cell.get(merge_attribute, 0)))
|
|
143
|
+
rows.append(values)
|
|
144
|
+
|
|
145
|
+
workbook = BytesIO()
|
|
146
|
+
with pd.ExcelWriter(workbook, engine="xlsxwriter") as writer:
|
|
147
|
+
pd.DataFrame(rows).to_excel(
|
|
148
|
+
writer,
|
|
149
|
+
sheet_name=sheet_name,
|
|
150
|
+
index=False,
|
|
151
|
+
header=False,
|
|
152
|
+
)
|
|
153
|
+
workbook.seek(0)
|
|
154
|
+
return workbook
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def add_excel_sheet(
|
|
158
|
+
cls,
|
|
159
|
+
df: pd.DataFrame,
|
|
160
|
+
*,
|
|
161
|
+
file_path: Path,
|
|
162
|
+
sheet_name: str = "Sheet1",
|
|
163
|
+
create_file_ok: bool = True,
|
|
164
|
+
replace_sheet_ok: bool = False,
|
|
165
|
+
writer_kwargs: Mapping[str, Any] = {},
|
|
166
|
+
exl_kwargs: Mapping[str, Any] = {},
|
|
167
|
+
col_mapping: ColMapping | None = None,
|
|
168
|
+
column_formatters: Sequence[ColumnFormatter] = [],
|
|
169
|
+
) -> None:
|
|
170
|
+
"""Add a DataFrame as a sheet to an Excel workbook, creating the file if needed.
|
|
171
|
+
|
|
172
|
+
When the file does not exist, it is created using xlsxwriter with full
|
|
173
|
+
formatting support. When the file exists, openpyxl is used in append
|
|
174
|
+
mode to preserve the formatting of existing sheets.
|
|
175
|
+
|
|
176
|
+
The target sheet is formatted as an Excel table with auto-fitted column
|
|
177
|
+
widths and optional column-specific formatting.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
df: The :class:`~pandas.DataFrame` to write.
|
|
181
|
+
file_path: Destination ``.xlsx`` file path. May be created or
|
|
182
|
+
modified depending on *create_file_ok* and *replace_sheet_ok*.
|
|
183
|
+
sheet_name: Name of the target worksheet. Defaults to
|
|
184
|
+
``"Sheet1"``.
|
|
185
|
+
create_file_ok: If ``True`` (default), allows creating the file if
|
|
186
|
+
it doesn't exist. If ``False``, raises :exc:`FileNotFoundError`
|
|
187
|
+
when the file is missing.
|
|
188
|
+
replace_sheet_ok: If ``True``, allows replacing an existing sheet
|
|
189
|
+
with the same name. If ``False`` (default), raises
|
|
190
|
+
:exc:`ValueError` when the sheet already exists.
|
|
191
|
+
writer_kwargs: Extra keyword arguments forwarded to
|
|
192
|
+
:class:`pandas.ExcelWriter`.
|
|
193
|
+
exl_kwargs: Extra keyword arguments forwarded to
|
|
194
|
+
:meth:`~pandas.DataFrame.to_excel`. The keys ``startrow``,
|
|
195
|
+
``header``, and ``index`` are pre-set but can be overridden.
|
|
196
|
+
col_mapping: A :class:`ColMapping` instance controlling column
|
|
197
|
+
selection, renaming, and ordering for the written sheet.
|
|
198
|
+
:attr:`~ColMapping.col_defs` entries are used only for their
|
|
199
|
+
``df_col_name`` (DataFrame column) and ``file_col_name``
|
|
200
|
+
(output column name); all other fields are ignored.
|
|
201
|
+
:attr:`~ColMapping.exclusions` columns are dropped.
|
|
202
|
+
When :attr:`~ColMapping.include_all` is ``True`` (default),
|
|
203
|
+
columns not mentioned are appended after the listed ones.
|
|
204
|
+
Defaults to ``None`` (all columns written as-is).
|
|
205
|
+
|
|
206
|
+
Example — exclude ``"internal_id"`` and rename ``"Amount"``::
|
|
207
|
+
|
|
208
|
+
ExcelFileMapper.add_excel_sheet(
|
|
209
|
+
df,
|
|
210
|
+
file_path=Path("out.xlsx"),
|
|
211
|
+
sheet_name="Data",
|
|
212
|
+
col_mapping=ColMapping(
|
|
213
|
+
col_defs=[
|
|
214
|
+
ColDefinition(df_col_name="date", file_col_name="Date"),
|
|
215
|
+
ColDefinition(df_col_name="Amount", file_col_name="Montant (€)"),
|
|
216
|
+
],
|
|
217
|
+
exclusions=["internal_id"],
|
|
218
|
+
),
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
column_formatters: Sequence of :class:`ColumnFormatter` instances,
|
|
222
|
+
each specifying columns to format and a formatter callable.
|
|
223
|
+
The formatter receives ``(workbook, worksheet, col_num)`` and
|
|
224
|
+
applies formatting to that column. Formatters are applied only
|
|
225
|
+
to the new/replacement sheet.
|
|
226
|
+
|
|
227
|
+
**Note:** When appending to an existing file, custom column
|
|
228
|
+
formatters are supported but are applied using openpyxl instead
|
|
229
|
+
of xlsxwriter, which may result in slightly different rendering.
|
|
230
|
+
|
|
231
|
+
The preferred way to build formatters is through the factory
|
|
232
|
+
class methods of :class:`ColumnFormatter`:
|
|
233
|
+
|
|
234
|
+
- :meth:`ColumnFormatter.currency` — applies a currency number
|
|
235
|
+
format; accepts an optional :class:`ExcelCurrency` (default
|
|
236
|
+
``EUR``).
|
|
237
|
+
- :meth:`ColumnFormatter.date` — applies a date number format;
|
|
238
|
+
accepts an optional *date_format* string (default
|
|
239
|
+
``"dd/mm/yyyy"``).
|
|
240
|
+
- :meth:`ColumnFormatter.text_wrap` — enables text wrapping.
|
|
241
|
+
|
|
242
|
+
Example — using the factory methods::
|
|
243
|
+
|
|
244
|
+
formatters = [
|
|
245
|
+
ColumnFormatter.date(columns=[0]),
|
|
246
|
+
ColumnFormatter.currency(columns=[2, 3], currency=ExcelCurrency.EUR),
|
|
247
|
+
ColumnFormatter.currency(columns=[4], currency=ExcelCurrency.USD),
|
|
248
|
+
ColumnFormatter.text_wrap(columns=[1]),
|
|
249
|
+
]
|
|
250
|
+
|
|
251
|
+
ExcelFileMapper.add_excel_sheet(
|
|
252
|
+
df,
|
|
253
|
+
file_path=Path("output.xlsx"),
|
|
254
|
+
sheet_name="Data",
|
|
255
|
+
column_formatters=formatters,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
Example — using a custom formatter callable directly::
|
|
259
|
+
|
|
260
|
+
def format_bold_header(
|
|
261
|
+
workbook: Workbook, worksheet: Worksheet, col_num: int
|
|
262
|
+
) -> None:
|
|
263
|
+
bold_fmt = workbook.add_format({"bold": True, "bg_color": "#DDEBF7"})
|
|
264
|
+
worksheet.set_column(col_num, col_num, cell_format=bold_fmt)
|
|
265
|
+
|
|
266
|
+
formatters = [
|
|
267
|
+
ColumnFormatter(columns=[0, 1], formatter=format_bold_header),
|
|
268
|
+
]
|
|
269
|
+
|
|
270
|
+
ExcelFileMapper.add_excel_sheet(
|
|
271
|
+
df,
|
|
272
|
+
file_path=Path("output.xlsx"),
|
|
273
|
+
sheet_name="Data",
|
|
274
|
+
column_formatters=formatters,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
Raises:
|
|
278
|
+
FileNotFoundError: If the file doesn't exist and *create_file_ok*
|
|
279
|
+
is ``False``.
|
|
280
|
+
ValueError: If the sheet exists and *replace_sheet_ok* is
|
|
281
|
+
``False``.
|
|
282
|
+
"""
|
|
283
|
+
# Expand user home directory if present in path
|
|
284
|
+
file_path = file_path.expanduser()
|
|
285
|
+
df = cls._apply_col_mapping_for_write(df, col_mapping)
|
|
286
|
+
|
|
287
|
+
file_exists = file_path.exists()
|
|
288
|
+
|
|
289
|
+
cls._logger.debug(f"Checking file {file_path}, exists={file_exists}")
|
|
290
|
+
|
|
291
|
+
# Check file existence policy
|
|
292
|
+
if not file_exists and not create_file_ok:
|
|
293
|
+
raise FileNotFoundError(
|
|
294
|
+
f"File {file_path} does not exist and create_file_ok is False"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
if not file_exists:
|
|
298
|
+
# Create new file with xlsxwriter (full formatting support)
|
|
299
|
+
cls._logger.info(f"Creating new file {file_path} with xlsxwriter")
|
|
300
|
+
cls._write_sheet_xlsxwriter(
|
|
301
|
+
df=df,
|
|
302
|
+
file_path=file_path,
|
|
303
|
+
sheet_name=sheet_name,
|
|
304
|
+
writer_kwargs=writer_kwargs,
|
|
305
|
+
exl_kwargs=exl_kwargs,
|
|
306
|
+
column_formatters=column_formatters,
|
|
307
|
+
)
|
|
308
|
+
else:
|
|
309
|
+
# Append to existing file with openpyxl (preserves existing sheets)
|
|
310
|
+
cls._logger.info(f"Appending to existing file {file_path} with openpyxl")
|
|
311
|
+
cls._append_sheet_openpyxl(
|
|
312
|
+
df=df,
|
|
313
|
+
file_path=file_path,
|
|
314
|
+
sheet_name=sheet_name,
|
|
315
|
+
replace_sheet_ok=replace_sheet_ok,
|
|
316
|
+
writer_kwargs=writer_kwargs,
|
|
317
|
+
exl_kwargs=exl_kwargs,
|
|
318
|
+
column_formatters=column_formatters,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def _sanitize_table_name(sheet_name: str) -> str:
|
|
323
|
+
"""Sanitize a sheet name for use as an Excel table name.
|
|
324
|
+
|
|
325
|
+
Excel table names have strict requirements:
|
|
326
|
+
- No spaces (replaced with underscores)
|
|
327
|
+
- Must start with a letter or underscore
|
|
328
|
+
- Can only contain letters, numbers, underscores, and periods
|
|
329
|
+
- Maximum 255 characters
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
sheet_name: The sheet name to sanitize.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
A valid Excel table name.
|
|
336
|
+
|
|
337
|
+
Example::
|
|
338
|
+
|
|
339
|
+
sanitized = DFFileMapper._sanitize_table_name("My Sheet Name")
|
|
340
|
+
# Returns "My_Sheet_Name"
|
|
341
|
+
"""
|
|
342
|
+
# Replace spaces with underscores
|
|
343
|
+
table_name = sheet_name.replace(" ", "_")
|
|
344
|
+
|
|
345
|
+
# Remove invalid characters (keep only letters, numbers, underscores, periods)
|
|
346
|
+
table_name = re.sub(r"[^A-Za-z0-9_.]", "_", table_name)
|
|
347
|
+
|
|
348
|
+
# Ensure it starts with a letter or underscore
|
|
349
|
+
if table_name and not (table_name[0].isalpha() or table_name[0] == "_"):
|
|
350
|
+
table_name = "_" + table_name
|
|
351
|
+
|
|
352
|
+
# Ensure it's not empty
|
|
353
|
+
if not table_name:
|
|
354
|
+
table_name = "Table"
|
|
355
|
+
|
|
356
|
+
# Limit to 255 characters
|
|
357
|
+
table_name = table_name[:255]
|
|
358
|
+
|
|
359
|
+
return table_name
|
|
360
|
+
|
|
361
|
+
@classmethod
|
|
362
|
+
def _write_sheet_xlsxwriter(
|
|
363
|
+
cls,
|
|
364
|
+
df: pd.DataFrame,
|
|
365
|
+
file_path: Path,
|
|
366
|
+
sheet_name: str,
|
|
367
|
+
writer_kwargs: Mapping[str, Any],
|
|
368
|
+
exl_kwargs: Mapping[str, Any],
|
|
369
|
+
column_formatters: Sequence[ColumnFormatter],
|
|
370
|
+
) -> None:
|
|
371
|
+
"""Write a sheet to a new Excel file using xlsxwriter.
|
|
372
|
+
|
|
373
|
+
Args:
|
|
374
|
+
df: DataFrame to write.
|
|
375
|
+
file_path: Destination file path.
|
|
376
|
+
sheet_name: Name of the sheet to create.
|
|
377
|
+
writer_kwargs: Arguments for ExcelWriter.
|
|
378
|
+
exl_kwargs: Arguments for to_excel.
|
|
379
|
+
column_formatters: Formatters to apply.
|
|
380
|
+
"""
|
|
381
|
+
with pd.ExcelWriter(
|
|
382
|
+
file_path, engine="xlsxwriter", mode="w", **writer_kwargs
|
|
383
|
+
) as writer:
|
|
384
|
+
def_pars: dict[str, Any] = {
|
|
385
|
+
"startrow": 1,
|
|
386
|
+
"header": False,
|
|
387
|
+
"index": False,
|
|
388
|
+
} | exl_kwargs # type: ignore
|
|
389
|
+
df.to_excel(writer, sheet_name=sheet_name, **def_pars)
|
|
390
|
+
|
|
391
|
+
# Get xlsxwriter objects
|
|
392
|
+
workbook: Workbook = writer.book
|
|
393
|
+
worksheet: Worksheet = writer.sheets[sheet_name]
|
|
394
|
+
|
|
395
|
+
# Get dataframe dimensions
|
|
396
|
+
max_row, max_col = df.shape
|
|
397
|
+
|
|
398
|
+
# Create column headers for Excel table
|
|
399
|
+
column_settings = [{"header": column} for column in df.columns]
|
|
400
|
+
|
|
401
|
+
# Create sanitized table name
|
|
402
|
+
table_name = cls._sanitize_table_name(sheet_name)
|
|
403
|
+
|
|
404
|
+
# Add Excel table structure
|
|
405
|
+
worksheet.add_table(
|
|
406
|
+
0,
|
|
407
|
+
0,
|
|
408
|
+
max_row,
|
|
409
|
+
max_col - 1,
|
|
410
|
+
{"columns": column_settings, "name": table_name},
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
worksheet.autofit()
|
|
414
|
+
|
|
415
|
+
# Apply column formatters AFTER autofit so that autofit's internal
|
|
416
|
+
# set_column() calls do not override the cell formats set here.
|
|
417
|
+
if column_formatters:
|
|
418
|
+
for col_formatter in column_formatters:
|
|
419
|
+
for col_num in col_formatter.resolved_indices(df.columns):
|
|
420
|
+
col_formatter.formatter(workbook, worksheet, col_num)
|
|
421
|
+
|
|
422
|
+
@classmethod
|
|
423
|
+
def _append_sheet_openpyxl(
|
|
424
|
+
cls,
|
|
425
|
+
df: pd.DataFrame,
|
|
426
|
+
file_path: Path,
|
|
427
|
+
sheet_name: str,
|
|
428
|
+
replace_sheet_ok: bool,
|
|
429
|
+
writer_kwargs: Mapping[str, Any],
|
|
430
|
+
exl_kwargs: Mapping[str, Any],
|
|
431
|
+
column_formatters: Sequence[ColumnFormatter],
|
|
432
|
+
) -> None:
|
|
433
|
+
"""Append a sheet to an existing Excel file using openpyxl.
|
|
434
|
+
|
|
435
|
+
This method preserves formatting of existing sheets.
|
|
436
|
+
|
|
437
|
+
Args:
|
|
438
|
+
df: DataFrame to write.
|
|
439
|
+
file_path: Destination file path.
|
|
440
|
+
sheet_name: Name of the sheet to create/replace.
|
|
441
|
+
replace_sheet_ok: If True, allows replacing existing sheet.
|
|
442
|
+
writer_kwargs: Arguments for ExcelWriter.
|
|
443
|
+
exl_kwargs: Arguments for to_excel.
|
|
444
|
+
column_formatters: Formatters to apply.
|
|
445
|
+
|
|
446
|
+
Raises:
|
|
447
|
+
ValueError: If sheet exists and replace_sheet_ok is False.
|
|
448
|
+
"""
|
|
449
|
+
from openpyxl import load_workbook
|
|
450
|
+
from openpyxl.styles import Font, Alignment, numbers
|
|
451
|
+
from openpyxl.worksheet.table import Table, TableStyleInfo
|
|
452
|
+
from openpyxl.utils import get_column_letter
|
|
453
|
+
|
|
454
|
+
# Open existing workbook
|
|
455
|
+
cls._logger.debug(f"Loading workbook {file_path}")
|
|
456
|
+
workbook = load_workbook(file_path)
|
|
457
|
+
|
|
458
|
+
# Check if sheet exists and handle replace policy
|
|
459
|
+
if sheet_name in workbook.sheetnames:
|
|
460
|
+
if not replace_sheet_ok:
|
|
461
|
+
workbook.close()
|
|
462
|
+
raise ValueError(
|
|
463
|
+
f"Sheet '{sheet_name}' already exists in {file_path} and replace_sheet_ok is False"
|
|
464
|
+
)
|
|
465
|
+
# Remove existing sheet
|
|
466
|
+
cls._logger.info(f"Removing existing sheet '{sheet_name}'")
|
|
467
|
+
del workbook[sheet_name]
|
|
468
|
+
|
|
469
|
+
# Create new sheet
|
|
470
|
+
cls._logger.info(f"Creating new sheet '{sheet_name}'")
|
|
471
|
+
worksheet = workbook.create_sheet(sheet_name)
|
|
472
|
+
|
|
473
|
+
# Write headers
|
|
474
|
+
for col_idx, column_name in enumerate(df.columns, start=1):
|
|
475
|
+
cell = worksheet.cell(row=1, column=col_idx)
|
|
476
|
+
cell.value = column_name
|
|
477
|
+
cell.font = Font(bold=True)
|
|
478
|
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
479
|
+
|
|
480
|
+
# Write data
|
|
481
|
+
for row_idx, row_data in enumerate(df.values, start=2):
|
|
482
|
+
for col_idx, value in enumerate(row_data, start=1):
|
|
483
|
+
worksheet.cell(row=row_idx, column=col_idx, value=value)
|
|
484
|
+
|
|
485
|
+
# Apply column formatters (adapt xlsxwriter formatters to openpyxl)
|
|
486
|
+
if column_formatters:
|
|
487
|
+
cls._logger.debug(
|
|
488
|
+
f"Applying {len(column_formatters)} column formatters with openpyxl"
|
|
489
|
+
)
|
|
490
|
+
for col_formatter in column_formatters:
|
|
491
|
+
for col_num in col_formatter.resolved_indices(df.columns):
|
|
492
|
+
cls._apply_openpyxl_formatter(
|
|
493
|
+
worksheet, col_num, col_formatter, len(df)
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
# Add table formatting
|
|
497
|
+
if len(df) > 0:
|
|
498
|
+
table_ref = f"A1:{get_column_letter(len(df.columns))}{len(df) + 1}"
|
|
499
|
+
# Sanitize table name to comply with Excel naming rules
|
|
500
|
+
table_name = cls._sanitize_table_name(sheet_name)
|
|
501
|
+
table = Table(displayName=table_name, ref=table_ref)
|
|
502
|
+
style = TableStyleInfo(
|
|
503
|
+
name="TableStyleMedium9",
|
|
504
|
+
showFirstColumn=False,
|
|
505
|
+
showLastColumn=False,
|
|
506
|
+
showRowStripes=True,
|
|
507
|
+
showColumnStripes=False,
|
|
508
|
+
)
|
|
509
|
+
table.tableStyleInfo = style
|
|
510
|
+
worksheet.add_table(table)
|
|
511
|
+
|
|
512
|
+
# Auto-fit columns
|
|
513
|
+
for col_idx, column_name in enumerate(df.columns, start=1):
|
|
514
|
+
col_letter = get_column_letter(col_idx)
|
|
515
|
+
max_length = len(str(column_name))
|
|
516
|
+
for row_idx in range(2, len(df) + 2):
|
|
517
|
+
cell_value = worksheet.cell(row=row_idx, column=col_idx).value
|
|
518
|
+
if cell_value:
|
|
519
|
+
max_length = max(max_length, len(str(cell_value)))
|
|
520
|
+
adjusted_width = min(max_length + 2, 50) # Cap at 50 characters
|
|
521
|
+
worksheet.column_dimensions[col_letter].width = adjusted_width
|
|
522
|
+
|
|
523
|
+
# Save workbook
|
|
524
|
+
cls._logger.info(f"Saving workbook to {file_path}")
|
|
525
|
+
workbook.save(file_path)
|
|
526
|
+
workbook.close()
|
|
527
|
+
|
|
528
|
+
@classmethod
|
|
529
|
+
def _apply_openpyxl_formatter(
|
|
530
|
+
cls,
|
|
531
|
+
worksheet: Any,
|
|
532
|
+
col_num: int,
|
|
533
|
+
col_formatter: ColumnFormatter,
|
|
534
|
+
num_rows: int,
|
|
535
|
+
) -> None:
|
|
536
|
+
"""Apply formatting to a column using openpyxl.
|
|
537
|
+
|
|
538
|
+
This method attempts to replicate xlsxwriter formatting using openpyxl.
|
|
539
|
+
It handles the built-in formatters (currency, date, text_wrap) but
|
|
540
|
+
custom formatters designed for xlsxwriter may not work correctly.
|
|
541
|
+
|
|
542
|
+
Args:
|
|
543
|
+
worksheet: openpyxl worksheet object.
|
|
544
|
+
col_num: Column number (0-based).
|
|
545
|
+
col_formatter: ColumnFormatter instance.
|
|
546
|
+
num_rows: Number of data rows (excluding header).
|
|
547
|
+
"""
|
|
548
|
+
from openpyxl.styles import Alignment, numbers
|
|
549
|
+
from openpyxl.utils import get_column_letter
|
|
550
|
+
|
|
551
|
+
col_letter = get_column_letter(col_num + 1)
|
|
552
|
+
|
|
553
|
+
# Try to detect formatter type by inspecting the formatter function
|
|
554
|
+
# This is a heuristic approach since we don't have explicit type info
|
|
555
|
+
formatter_name = col_formatter.formatter.__name__
|
|
556
|
+
|
|
557
|
+
# Check if this is a currency formatter
|
|
558
|
+
if "currency" in formatter_name or "_fmt" in formatter_name:
|
|
559
|
+
# Try to extract number format from the formatter
|
|
560
|
+
# This is a best-effort approach for built-in formatters
|
|
561
|
+
try:
|
|
562
|
+
# Create a dummy xlsxwriter-compatible object to extract format
|
|
563
|
+
class DummyWorkbook:
|
|
564
|
+
"""Dummy workbook to capture format specifications."""
|
|
565
|
+
|
|
566
|
+
def __init__(self) -> None:
|
|
567
|
+
self.formats: list[Any] = []
|
|
568
|
+
|
|
569
|
+
def add_format(self, fmt_dict: Any) -> Any:
|
|
570
|
+
"""Capture format dictionary."""
|
|
571
|
+
self.formats.append(fmt_dict)
|
|
572
|
+
return fmt_dict
|
|
573
|
+
|
|
574
|
+
class DummyWorksheet:
|
|
575
|
+
"""Dummy worksheet to capture column settings."""
|
|
576
|
+
|
|
577
|
+
def __init__(self) -> None:
|
|
578
|
+
self.column_formats: dict[Any, Any] = {}
|
|
579
|
+
|
|
580
|
+
def set_column(
|
|
581
|
+
self,
|
|
582
|
+
first_col: Any,
|
|
583
|
+
last_col: Any,
|
|
584
|
+
width: Any = None,
|
|
585
|
+
cell_format: Any = None,
|
|
586
|
+
options: Any = None,
|
|
587
|
+
) -> None:
|
|
588
|
+
"""Capture column format."""
|
|
589
|
+
self.column_formats[first_col] = cell_format
|
|
590
|
+
|
|
591
|
+
dummy_wb = DummyWorkbook()
|
|
592
|
+
dummy_ws = DummyWorksheet()
|
|
593
|
+
|
|
594
|
+
# Call the formatter to extract format info. DummyWorkbook/DummyWorksheet
|
|
595
|
+
# only duck-type the subset of the xlsxwriter API used by the built-in
|
|
596
|
+
# formatters (add_format/set_column), so we cast them to satisfy the
|
|
597
|
+
# formatter's declared signature.
|
|
598
|
+
col_formatter.formatter(
|
|
599
|
+
cast(Workbook, dummy_wb), cast(Worksheet, dummy_ws), col_num
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
# Apply extracted format to all cells in the column
|
|
603
|
+
if dummy_wb.formats:
|
|
604
|
+
fmt = dummy_wb.formats[0]
|
|
605
|
+
if "num_format" in fmt:
|
|
606
|
+
num_format = fmt["num_format"]
|
|
607
|
+
for row_idx in range(2, num_rows + 2): # Skip header
|
|
608
|
+
cell = worksheet.cell(row=row_idx, column=col_num + 1)
|
|
609
|
+
cell.number_format = num_format
|
|
610
|
+
if "text_wrap" in fmt or (
|
|
611
|
+
hasattr(fmt, "set_text_wrap")
|
|
612
|
+
if not isinstance(fmt, dict)
|
|
613
|
+
else False
|
|
614
|
+
):
|
|
615
|
+
for row_idx in range(2, num_rows + 2):
|
|
616
|
+
cell = worksheet.cell(row=row_idx, column=col_num + 1)
|
|
617
|
+
cell.alignment = Alignment(wrap_text=True)
|
|
618
|
+
|
|
619
|
+
except Exception as e:
|
|
620
|
+
cls._logger.warning(
|
|
621
|
+
f"Could not apply custom formatter to column {col_num}: {e}. "
|
|
622
|
+
"Custom formatters may not work correctly when appending to existing files."
|
|
623
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pycraftbox-excel
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Excel file utilities for pycraftbox
|
|
5
|
+
Project-URL: Homepage, https://gitlab.com/erch/pycraftbox
|
|
6
|
+
Project-URL: Repository, https://gitlab.com/erch/pycraftbox
|
|
7
|
+
Project-URL: Issues, https://gitlab.com/erch/pycraftbox/-/issues
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Requires-Dist: openpyxl>=3.1.5
|
|
10
|
+
Requires-Dist: pycraftbox-dataframe<5,>=4
|
|
11
|
+
Requires-Dist: xlsxwriter>=3.2.9
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
pycraftbox/excel/__init__.py,sha256=cGA2KdMnJr6HO3CNkMcEbLa_CdvzKBrt9sBKezVsi20,200
|
|
2
|
+
pycraftbox/excel/formatters.py,sha256=AhvC7guV9haoW7Ak6GGHT6pAwOqP2tNqNP93G1ZZYoI,6272
|
|
3
|
+
pycraftbox/excel/mapper.py,sha256=S70bEL58KzimbdcpN6wuMOh6nNmoFmMvNco7rZ2ElyM,26038
|
|
4
|
+
pycraftbox_excel-4.0.0.dist-info/METADATA,sha256=jSSc4t3IiMSxjPkqKJzlJXSrrOIgyVe7Y5HbyzX0qrM,418
|
|
5
|
+
pycraftbox_excel-4.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
pycraftbox_excel-4.0.0.dist-info/RECORD,,
|