DataFrame export¶
df_to_xlsx writes a single pandas or polars DataFrame to one worksheet. It is the
main entry point, and every formatting, table, chart, and validation option in the rest
of these pages is a keyword argument to it.
DataFrame Export (pandas/polars)¶
import xlsxturbo
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'age': [30, 25],
'salary': [50000.50, 60000.75],
'active': [True, False]
})
# Export to XLSX (preserves types: int, float, bool, date, datetime)
rows, cols = xlsxturbo.df_to_xlsx(df, "output.xlsx")
print(f"Wrote {rows} rows and {cols} columns")
# Works with polars too!
import polars as pl
df_polars = pl.DataFrame({'x': [1, 2, 3], 'y': [4.0, 5.0, 6.0]})
xlsxturbo.df_to_xlsx(df_polars, "polars_output.xlsx", sheet_name="Data")
Leaving rows above the data¶
startrow is the zero-based row of the header, as in pandas' to_excel; the data starts
on the row below it. The rows above are free for a title or notes:
xlsxturbo.df_to_xlsx(
df,
"report.xlsx",
startrow=2,
table_style="Medium2",
merged_ranges=[("A1:D1", "Q3 report", {"bold": True, "font_size": 14})],
cells={"A2": "Revenue by region, in EUR"},
)
- Moves with the frame: the header, the data, the Excel table,
freeze_panes(the rows above freeze too),formula_columns(their{row}is the real sheet row),conditional_formatsandvalidations. - Stays where you put it: every cell reference, in
cells,merged_ranges,rich_text,hyperlinks,comments,images,chartsandsparklines, and the row indexes inrow_heights. A chart over the data therefore names the moved rows, e.g.Sheet1!$B$4:$B$10forstartrow=2. - The returned row count is the rows written, header included, without the offset.
- A frame that does not fit below the offset (Excel has 1,048,576 rows) is refused
before anything is written. With
header=Falsethe first data row isstartrow.
In dfs_to_xlsx, startrow is a workbook default that each sheet can override in its
options dict. It also works with constant_memory=True.
Freezing rows and columns¶
freeze_panes=True freezes the header row. To keep a key column in view as well, or to
freeze at another row, pass (row, col): the zero-based cell that becomes the top-left
corner of the scrolling area, as in XlsxWriter's freeze_panes(row, col).
# The header row and the first column stay in view
xlsxturbo.df_to_xlsx(df, "wide.xlsx", freeze_panes=(1, 1))
# Three title rows, the header below them, and the first column
xlsxturbo.df_to_xlsx(df, "matrix.xlsx", startrow=3, freeze_panes=(4, 1))
True follows startrow and does nothing with header=False. A tuple is taken as
given, so it does not move with startrow. (0, 0) freezes nothing.
Filter buttons without a table¶
autofilter=True puts filter buttons on the header row and leaves the range a plain
range. Use it when the sheet must not contain an Excel table: a title in merged cells
above the header, a reader that does not accept tables, or a table name that is already
taken.
- The filter covers the header row and the data rows,
formula_columnsincluded, and it followsstartrow. A frame without rows gets the buttons on the header row alone. - Only the buttons are added. No filter condition is set and no row is hidden.
autofilter=Truewith atable_styleraisesConfigurationError, because a table has its own filter. So doesautofilter=Truewithheader=False: the first data row would carry the buttons and drop out of the filter.
For filter buttons with banded rows and a named range, use an Excel table.
Sheet tab colour¶
tab_color colours the sheet tab. It takes '#RRGGBB' or one of the colour names the
format options take, such as 'red'.
To colour tabs by group, set it per sheet: see Multi-sheet workbooks.
freeze_panes, autofilter and tab_color are properties of the sheet and not cell
writes, so all three also work with constant_memory=True.
Writing to memory instead of a file¶
output_path also accepts a binary file-like object: io.BytesIO, a file opened with
"wb", or anything else with a write(bytes) method. This is the shape for a web
download or an object-storage upload, where a temporary file is only plumbing.
dfs_to_xlsx and csv_to_xlsx accept the same targets.
import io
buffer = io.BytesIO()
xlsxturbo.df_to_xlsx(df, buffer, autofit=True)
data = buffer.getvalue() # the complete .xlsx file
In a FastAPI endpoint:
from fastapi import Response
@app.get("/report.xlsx")
def report() -> Response:
buffer = io.BytesIO()
xlsxturbo.df_to_xlsx(load_report(), buffer, table_style="Medium9")
return Response(
content=buffer.getvalue(),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": 'attachment; filename="report.xlsx"'},
)
What to expect:
- The whole file is held in memory before it is written, compressed. With
constant_memory=Truethe worksheet data is still staged on disk while rows are written, but the finished archive is not. - Conversion and workbook-save failures write nothing into the object. A failure while delivering the finished archive can leave partial bytes in the object; unlike a path export, an arbitrary writer cannot be rolled back.
- The object stays open, at its new position. Call
buffer.getvalue(), orbuffer.seek(0)before handing it to something that reads it. - A text stream is refused with a
ConfigurationTypeError. An.xlsxfile is binary, so open files with"wb", not"w". - A
write()that returns fewer bytes than it was given is called again with the rest; one that returnsNone(Django'sHttpResponse, for example) is taken to have accepted everything, except forio.RawIOBasestreams. TheirNonemeans the stream would block, and raisesFileErrorwitherrno.EAGAIN.
Type Detection Examples¶
| CSV Value | Excel Type | Notes |
|---|---|---|
123 |
Number | Integer |
3.14159 |
Number | Float |
true / FALSE |
Boolean | Case insensitive |
2024-01-15 |
Date | Formatted as date |
2024-01-15T10:30:00 |
DateTime | ISO 8601 format |
NaN / inf / Infinity |
Empty | Any spelling of a non-finite number — see below |
1899-12-30 … 1900-02-28 |
Text | Excel numbers these a day out — see below |
hello world |
Text | Default |
Supported date formats: YYYY-MM-DD, YYYY/MM/DD, DD-MM-YYYY, DD/MM/YYYY, MM-DD-YYYY, MM/DD/YYYY
Non-finite numbers, and a trap in text columns¶
Excel has no NaN or infinity, so a CSV field holding one becomes an empty cell. That covers
every spelling the number parser accepts, in any case and with an optional sign: nan,
NaN, +nan, inf, -Inf, infinity, INFINITY.
The trap is that some of those are also ordinary words. A text column whose values include
NAN, Inf or Infinity loses them to empty cells, because nothing distinguishes the word
from the number at that point. A spelling the parser does not accept, such as Inf., stays
text. csv_to_xlsx takes no column_formats, so if a column is meant to be text, read the
CSV into a DataFrame with that column as strings (for pandas, dtype=str,
keep_default_na=False) and export it with df_to_xlsx, or check for the spellings above
before exporting.
Dates before 1900-03-01¶
Excel's serial numbering assumes a 1900-02-29 that never existed, so every date before 1900-03-01 is numbered one day later than the real calendar. Rather than write a date that renders on the wrong day, xlsxturbo writes those as text, exactly as they appeared in the input. Dates from 1900-03-01 onward — serial 61 up to Excel's last day, 9999-12-31 — are unaffected.
Very large integers¶
An integer whose magnitude exceeds 2^53 (9,007,199,254,740,992) cannot be stored as an Excel number without changing value, because Excel stores every number as a double. Those are written as text so no digits are lost. Anything at or below that magnitude is a normal number.
Durations¶
DataFrame columns follow the same mapping, with one addition worth knowing: durations are not written as Excel durations, and what is written depends on how the column reaches the writer. For a duration of one day:
| Column | Written |
|---|---|
| pandas, every column of the frame a timedelta, unit seconds to microseconds | Text in the column's unit: 86400 seconds, 86400000 milliseconds, 86400000000 microseconds |
| pandas, every column of the frame a timedelta, unit nanoseconds (the pandas 2 default) | The number of nanoseconds, 86400000000000 |
| pandas timedelta column in a frame with any other column type | Text, 1 days 00:00:00 |
polars Duration, or datetime.timedelta objects |
Text, 1 day, 0:00:00 |
A missing duration (NaT, None, a polars null) is an empty cell in every case. Excel
has no duration type: it shows a number of days as a duration. So convert first, with
df["elapsed"] / pd.Timedelta(days=1) (pandas) or
pl.col("elapsed").dt.total_microseconds() / 86_400_000_000 (polars), and apply a
num_format such as [h]:mm:ss. For a plain number in another unit,
df["elapsed"].dt.total_seconds() gives seconds.