Writing¶
New workbooks: the writers, sheet options and DataFrame export.
XlsxWriter
¶
XlsxWriter(file: WriteTarget, compression_level: int = 3, use_shared_strings: bool = True, spool_max_bytes: int = DEFAULT_SPOOL_BYTES, strings_to_formulas: bool = False, strings_to_numbers: bool = False, strings_to_urls: bool = False, nan_inf_to_errors: bool = False, **unknown: object)
Bases: _XlsxSheetMixin, _XlsxStylesMixin, _XlsxPartsMixin, _XlsxSheetXmlMixin, WriterFrontEnd, StagedWriter, DocumentPropertiesMixin
Write XLSX workbooks with a row-oriented API.
A writer collects sheets, styles, tables, charts and other objects, then
publishes the package when the with block exits. Rows are consumed once,
so a generator or a database cursor can be passed straight to
write_sheet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
WriteTarget
|
A path or a binary file object to write. |
required |
compression_level
|
int
|
ZIP compression level, 0-9 (default 3). |
3
|
use_shared_strings
|
bool
|
Store every distinct string once (default). Set it
to |
True
|
spool_max_bytes
|
int
|
Bytes kept in memory before sheet rows spill to a temporary file. |
DEFAULT_SPOOL_BYTES
|
Examples:
Write a styled report and read it back:
from xlspy import ExcelReader, F, Style, XlsxWriter
with XlsxWriter("report.xlsx") as workbook:
workbook.add_sheet("Sales")
workbook.write_sheet(
[["Product", "Revenue"], ["Coffee", (12500, F.THOUSANDS_SEP)]],
header_style=Style(bold=True, fill="183C52", font_color="FFFFFF"),
freeze_panes="A2",
)
with ExcelReader("report.xlsx") as reader:
print(reader.read_all("Sales"))
See Also
XlsbWriter for the binary XLSB format with the same API, and
to_xlsx for a DataFrame one-liner.
Source code in src/xlspy/xlsx_writer.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
add_vba_project
¶
add_vba_project(project: str | PathLike[str] | bytes | bytearray | memoryview | Any) -> None
Embed a VBA project (vbaProject.bin) in the workbook.
The package becomes macro-enabled, so save it with an .xlsm (or
.xltm) extension. project may be a path, bytes or a binary file
object. Call set_vba_name to set the project's code name.
Source code in src/xlspy/xlsx_writer.py
323 324 325 326 327 328 329 330 331 | |
set_vba_name
¶
set_vba_name(name: str) -> None
Set the workbook code name (workbookPr/@codeName) for the VBA project.
Source code in src/xlspy/xlsx_writer.py
333 334 335 336 | |
set_defined_name
¶
set_defined_name(definition: DefinedName) -> None
Set a global or worksheet-local name; local titles are checked on save.
Source code in src/xlspy/xlsx_writer.py
338 339 340 341 342 343 | |
get_defined_names
¶
get_defined_names() -> list[DefinedName]
The defined names set so far.
Source code in src/xlspy/xlsx_writer.py
345 346 347 | |
remove_defined_name
¶
remove_defined_name(name: str, scope: str | None = None) -> None
Remove a defined name; with scope, the one local to that sheet.
Source code in src/xlspy/xlsx_writer.py
349 350 351 352 353 | |
set_properties
¶
set_properties(*, title: str | None = None, subject: str | None = None, author: str | None = None, manager: str | None = None, company: str | None = None, category: str | None = None, keywords: str | None = None, comments: str | None = None, status: str | None = None, created: datetime | None = None, custom: dict | None = None) -> None
Set the document properties shown in Excel under File > Info.
Text fields are optional strings. created defaults to the time of
the call; a naive datetime is taken as UTC. custom maps property
names to str, int, float, bool, date or datetime values and appears
under File > Info > Properties > Advanced Properties > Custom.
Calling it again replaces every earlier value.
Source code in src/xlspy/doc_properties.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
set_workbook_protection
¶
set_workbook_protection(protection: WorkbookProtection) -> None
Lock the workbook structure, with a password when one is given.
Source code in src/xlspy/_output.py
195 196 197 198 199 200 | |
save
¶
save() -> None
Write the workbook parts. The file is published when the writer closes.
Source code in src/xlspy/_output.py
238 239 240 241 242 243 244 245 246 | |
close
¶
close() -> None
Close the writer, publishing the workbook if save() succeeded.
Source code in src/xlspy/_output.py
248 249 250 | |
write_sheet
¶
write_sheet(data: Iterable[list[Any]], *, options: SheetOptions | None = None, **kwargs: Any) -> None
Write rows to the current sheet.
data is consumed once, row by row. Sheet settings come from options
(a SheetOptions) or from keyword arguments with the same names; a
keyword argument overrides the matching field of options. The rows are
encoded into a temporary spool (kept in memory up to spool_max_bytes,
then on disk), so memory does not grow with the number of rows. Hyperlinks,
formulas and the other options are described in the documentation.
Source code in src/xlspy/_xlsx_writer_sheet.py
107 108 109 110 111 112 113 114 115 116 117 118 | |
write_dataframe
¶
write_dataframe(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict | None = None, *, header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: list[ExcelTable] | tuple[ExcelTable, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: list | tuple | None = None, data_validations: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, comments: Mapping[str, Comment] | None = None, threaded_comments: Mapping[str, Any] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, tab_color: Color | str | None = None, zoom: int | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, pivots: list | tuple | None = None) -> None
Write a pandas or polars DataFrame to the current sheet.
pandas and polars are optional: they are imported lazily only when a DataFrame is actually passed in.
Parameters¶
df:
A pandas.DataFrame or polars.DataFrame.
include_index:
pandas only -- prepend the index as leading column(s).
na_rep:
Value for missing cells, defaults to None (empty cell).
formats:
Optional {column_name: format_string} mapping (see xlspy.F).
Source code in src/xlspy/_xlsx_writer_sheet.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
XlsbWriter
¶
XlsbWriter(file: WriteTarget, compression_level: int = 3, use_shared_strings: bool = True, strings_to_formulas: bool = False, strings_to_numbers: bool = False, strings_to_urls: bool = False, nan_inf_to_errors: bool = False, **unknown: object)
Bases: _XlsbStylesMixin, _XlsbPartsMixin, _XlsbSheetMixin, _XlsbViewsMixin, _XlsbBinMixin, _XlsbStringsMixin, WriterFrontEnd, StagedWriter, XlsbWriterMetadata, DocumentPropertiesMixin
Write XLSB workbooks with the same API as XlsxWriter.
XLSB is Excel's binary workbook format. It is faster and smaller than XLSX for large exports, at the cost of narrower support in third-party readers. Rows are consumed once and encoded as they are produced, so memory does not grow with the number of rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
WriteTarget
|
A path or a binary file object to write. |
required |
compression_level
|
int
|
ZIP compression level, 0-9 (default 3). |
3
|
use_shared_strings
|
bool
|
Store every distinct string once (default). Set it
to |
True
|
Examples:
Write the same report as XLSB:
from xlspy import F, Style, XlsbWriter
with XlsbWriter("report.xlsb") as workbook:
workbook.add_sheet("Sales")
workbook.write_sheet(
[["Product", "Revenue"], ["Coffee", (12500, F.THOUSANDS_SEP)]],
header_style=Style(bold=True, fill="183C52", font_color="FFFFFF"),
freeze_panes="A2",
)
Stream a million rows from a generator with bounded memory:
from xlspy import XlsbWriter
def rows(count):
for i in range(count):
yield [i, f"row-{i}", i * 1.5]
with XlsbWriter("large.xlsb", use_shared_strings=False) as workbook:
workbook.add_sheet("Data")
workbook.write_sheet(rows(1_000_000))
See Also
XlsxWriter for maximum compatibility, and to_xlsb for a DataFrame
one-liner. XLSB formulas use a binary grammar; an unsupported token
raises UnsupportedFeatureError instead of writing a broken file.
Source code in src/xlspy/writer.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
set_properties
¶
set_properties(*, title: str | None = None, subject: str | None = None, author: str | None = None, manager: str | None = None, company: str | None = None, category: str | None = None, keywords: str | None = None, comments: str | None = None, status: str | None = None, created: datetime | None = None, custom: dict | None = None) -> None
Set the document properties shown in Excel under File > Info.
Text fields are optional strings. created defaults to the time of
the call; a naive datetime is taken as UTC. custom maps property
names to str, int, float, bool, date or datetime values and appears
under File > Info > Properties > Advanced Properties > Custom.
Calling it again replaces every earlier value.
Source code in src/xlspy/doc_properties.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
add_sheet
¶
add_sheet(sheet_name: str, hidden: bool = False) -> None
Start a new sheet; the next write_sheet call fills it.
hidden=True hides the sheet.
Source code in src/xlspy/_writer_common.py
154 155 156 157 158 159 160 161 | |
set_defined_name
¶
set_defined_name(definition: DefinedName) -> None
Add a defined name, replacing one with the same name and scope.
Source code in src/xlspy/_xlsb_writer.py
40 41 42 43 | |
get_defined_names
¶
get_defined_names() -> list[DefinedName]
The defined names set so far.
Source code in src/xlspy/_xlsb_writer.py
45 46 47 | |
remove_defined_name
¶
remove_defined_name(name: str, scope: str | None = None) -> None
Remove a defined name; with scope, the one local to that sheet.
Source code in src/xlspy/_xlsb_writer.py
49 50 51 52 53 54 | |
set_workbook_protection
¶
set_workbook_protection(protection: WorkbookProtection) -> None
Lock the workbook structure, with a password when one is given.
Source code in src/xlspy/_output.py
195 196 197 198 199 200 | |
save
¶
save() -> None
Write the workbook parts. The file is published when the writer closes.
Source code in src/xlspy/_output.py
238 239 240 241 242 243 244 245 246 | |
close
¶
close() -> None
Close the writer, publishing the workbook if save() succeeded.
Source code in src/xlspy/_output.py
248 249 250 | |
write_sheet
¶
write_sheet(data: Iterable[list[Any]], *, options: SheetOptions | None = None, **kwargs: Any) -> None
Write rows to the current sheet.
Sheet settings come from options (a SheetOptions) or from keyword
arguments with the same names; a keyword argument overrides the matching
field of options.
Source code in src/xlspy/_xlsb_writer_sheet.py
40 41 42 43 44 45 46 47 48 | |
write_dataframe
¶
write_dataframe(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict | None = None, *, header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, auto_filter_ref: str | None = None, charts: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, data_validations: list | tuple | None = None, tables: list | tuple | None = None, conditional_formats: list | tuple | None = None, comments: Mapping[str, Comment] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, tab_color: Color | str | None = None, zoom: int | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, pivots: list | tuple | None = None) -> None
Write a pandas or polars DataFrame to the current sheet.
pandas and polars are optional: they are imported lazily only when a DataFrame is actually passed in.
Parameters¶
df:
A pandas.DataFrame or polars.DataFrame.
include_index:
pandas only -- prepend the index as leading column(s).
na_rep:
Value for missing cells, defaults to None (empty cell).
formats:
Optional {column_name: format_string} mapping (see xlspy.F).
Source code in src/xlspy/_xlsb_writer_sheet.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
SheetOptions
dataclass
¶
SheetOptions(header_style: Style | None = None, styles: dict[str, Style] | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: list | tuple | None = None, column_widths: dict | None = None, autofit_rows: int = 1000, autofit_padding: float = 0.0, hidden_columns: list | tuple | set | None = None, row_heights: dict | None = None, hidden_rows: list | tuple | set | None = None, row_groups: list | tuple | None = None, column_groups: list | tuple | None = None, freeze_panes: str | None = None, auto_filter: bool | None = None, auto_filter_ref: str | None = None, charts: list | tuple | None = None, data_validations: list | tuple | None = None, images: list | tuple | None = None, print_settings: PrintSettings | None = None, comments: Mapping[str, Any] | None = None, threaded_comments: Mapping[str, Any] | None = None, sheet_protection: SheetProtection | None = None, show_grid_lines: bool = True, header_rows: int = 1, tab_color: Color | str | None = None, zoom: int | None = None, ignored_errors: list | tuple | None = None, sparklines: list | tuple | None = None, slicers: list | tuple | None = None, pivots: list | tuple | None = None, shapes: list | tuple | None = None, show_row_col_headers: bool = True, show_zero_values: bool = True, right_to_left: bool = False, sort_state: Any | None = None)
Every option of write_sheet except the rows. Defaults match the call defaults.
F
¶
Format string constants for cell number formatting.
Use with writers by passing (value, format_string) tuples: writer.write_sheet([ ["Name", "Value"], ["Revenue", (100000, F.THOUSANDS_SEP)], ["Date", (date(2026, 6, 1), F.DATE_SHORT)], ])
to_xlsx
¶
to_xlsx(df: Any, path: _Target, sheet_name: str = 'Sheet1', *, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None, header_style: Style | None = None, styles: dict | None = None, merges: list[str] | tuple[str, ...] | None = None, conditional_formats: list | tuple | None = None, tables: Any = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: Any = None, row_heights: dict | None = None, hidden_rows: Any = None, row_groups: Any = None, column_groups: Any = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: Any = None, comments: Any = None, threaded_comments: Any = None, sheet_protection: SheetProtection | None = None, **writer_kwargs: Any) -> _Target
Write a DataFrame straight to an .xlsx file and return path.
A failed conversion leaves path as it was: the writer stages the file
and publishes it only on success.
Examples:
import pandas as pd
from xlspy import to_xlsx
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
to_xlsx(df, "people.xlsx")
All sheet options of write_dataframe are accepted as keywords:
to_xlsx(df, "people.xlsx", freeze_panes="A2", include_index=True)
See Also
to_xlsb for the binary format, and XlsxWriter.write_dataframe for
writing into a workbook that already has sheets and objects.
Source code in src/xlspy/dataframe.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
to_xlsb
¶
to_xlsb(df: Any, path: _Target, sheet_name: str = 'Sheet1', *, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None, header_style: Style | None = None, styles: dict | None = None, merges: list[str] | tuple[str, ...] | None = None, column_widths: dict | None = None, autofit_rows: int | None = 1000, autofit_padding: float = 0.0, hidden_columns: Any = None, row_heights: dict | None = None, hidden_rows: Any = None, row_groups: Any = None, column_groups: Any = None, freeze_panes: str | None = None, auto_filter: bool | None = None, charts: Any = None, tables: Any = None, conditional_formats: Any = None, comments: Any = None, sheet_protection: SheetProtection | None = None, **writer_kwargs: Any) -> _Target
Write a DataFrame straight to an .xlsb file and return path.
A failed conversion leaves path as it was: the writer stages the file
and publishes it only on success.
Examples:
import polars as pl
from xlspy import to_xlsb
df = pl.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
to_xlsb(df, "people.xlsb")
The result is a binary XLSB workbook with a single Sheet1. Use
XlsbWriter.write_dataframe to add more sheets, styles or charts.
See Also
to_xlsx for maximum compatibility, and XlsbWriter for the full
writer API.
Source code in src/xlspy/dataframe.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
dataframe_to_rows
¶
dataframe_to_rows(df: Any, include_index: bool = False, na_rep: Any = None, formats: dict[str, str] | None = None) -> Iterator[list[Any]]
Yield a pandas or polars DataFrame as rows ready for write_sheet.
Parameters¶
df:
A pandas.DataFrame or polars.DataFrame.
include_index:
pandas only -- prepend the index (all levels of a MultiIndex) as
leading columns. polars has no index and raises ValueError.
na_rep:
Value written for missing cells (None/NaN/NaT/NA).
Defaults to None, i.e. an empty cell.
formats:
Optional mapping of column name to a format string (see xlspy.F),
e.g. {"date": F.DATE_ISO, "price": F.CURRENCY_PLN}.
The result is a generator, so the XLSB writer keeps streaming row by row.
Source code in src/xlspy/_dataframe_rows.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |