
Writing an XLSX file in Python comes down to three moves: create a workbook, put values into cells, and save. The practical questions start right after — where the data comes from (a few literals, a pandas DataFrame, a list of rows), whether the cells need types and formats, and whether you are creating a new file or appending to one that already exists. Each of those situations calls for a slightly different piece of code.
This tutorial works through them in order. You will create a first XLSX file with Spire.XLS for Python — with the openpyxl equivalent alongside each example — export a DataFrame two ways, write typed cell values and formulas, append rows to an existing file without overwriting it, and finish with basic formatting and multi-sheet workbooks. Every snippet in this article was run and verified before publication, and the screenshots show the actual output files.
Spire.XLS is a standalone Excel-processing API for Python. Beyond creating and editing workbooks, it provides a formula calculation engine and conversion options for PDF, HTML, and images, while supporting formats such as XLS, XLSX, XLSB, XLSM, and ODS. It does not require Microsoft Excel to be installed. In this tutorial it handles the writing tasks; when the job grows beyond generating a file, the same API carries the rest of the pipeline.
Quick Start: Create an XLSX File with Python
Install the libraries first — you only need the ones your examples use. pip is case-insensitive, so the package name matches the official tutorials either way you type it:
pip install Spire.XLS # for the Spire.XLS examples
pip install openpyxl pandas # for the openpyxl and pandas examples
Spire.XLS for Python
from spire.xls import Workbook, ExcelVersion
wb = Workbook()
wb.Worksheets.Clear() # a new workbook opens with 3 empty default sheets; clear them
sheet = wb.Worksheets.Add("Products")
sheet.Range["A1"].Text = "Product"
sheet.Range["B1"].Text = "Price"
sheet.Range["A2"].Text = "Keyboard"
sheet.Range["B2"].NumberValue = 29.9
wb.SaveToFile("output/quickstart_spire.xlsx", ExcelVersion.Version2016)
wb.Dispose()
The Spire.XLS flow has two details worth noticing up front. A new Workbook() opens with three empty default sheets (Sheet1 through Sheet3), so the example clears them and adds one named "Products" — that way the saved file contains exactly the sheet you wrote. And values go in through typed properties: Text for strings, NumberValue for numbers. This explicit assignment is useful when you want to control exactly how values are stored in the workbook, especially when building reports with mixed data types. SaveToFile writes the file in the format you name, and Dispose releases the workbook's native resources — call it when you are done with any Spire workbook, particularly in long-running scripts.
A free edition is also available (pip install Spire.XLS.free). Per its published limits, the 5-worksheet and 200-row restrictions apply to XLS files, while loading and saving XLSX files carry no such stated limits; PDF conversion is capped at the first three pages and technical support is not included. We verified the quick start above on the free edition (14.12.4) as well. If you are still deciding which library to commit to, we ran a hands-on comparison of openpyxl, XlsxWriter, pandas, and Spire.XLS on the same job, including a large-sheet benchmark.
openpyxl
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws["A1"] = "Product"
ws["B1"] = "Price"
ws["A2"] = "Keyboard"
ws["B2"] = 29.9
wb.save("output/quickstart_openpyxl.xlsx")
Workbook() starts a file with one active sheet. Assigning a Python value to ws["A1"] writes it and lets openpyxl infer the cell type — the string lands as text, 29.9 as a number. wb.save writes the file. The snippets in this article save into an output/ directory next to your script; create the folder before running, or adjust the path to taste.

Export a Pandas DataFrame to an XLSX File
Most XLSX files written from Python carry data that already lives in a pandas DataFrame. There are two ways to get it into a file, and they serve different follow-up work.
Plan A: let pandas write the file
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob", "Cathy"],
"Score": [90, 85, 78],
"Price": [12.5, 9.99, 120.75],
"Registered": pd.to_datetime(["2026-01-15", "2026-03-02", "2026-06-30"]),
"Active": [True, False, True],
"Note": ["ok", None, None],
})
with pd.ExcelWriter("output/df_export.xlsx", datetime_format="YYYY-MM-DD") as w:
df.to_excel(w, index=False) # index=False drops the row-index column
# pandas writes no column widths — widen the date column or Excel shows ###
from openpyxl import load_workbook
wb = load_workbook("output/df_export.xlsx")
wb.active.column_dimensions["D"].width = 13
wb.save("output/df_export.xlsx")
# multiple worksheets
summary = df[["Name", "Score"]].groupby("Name", as_index=False).min()
with pd.ExcelWriter("output/df_multi.xlsx", datetime_format="YYYY-MM-DD") as writer:
df.to_excel(writer, sheet_name="Orders", index=False)
summary.to_excel(writer, sheet_name="Summary", index=False)
to_excel(index=False) drops the row-index column so the sheet starts with your headers; sheet_name names the sheet; and an ExcelWriter block writes several sheets into one workbook. The actual file writing is delegated to an engine such as openpyxl or XlsxWriter. Types survive the trip: integers, floats, datetimes, and booleans land as their Excel counterparts, and None or NaN becomes an empty cell. Two cosmetic gotchas: pandas formats datetime cells as date-with-time (yyyy-mm-dd h:mm:ss, 19 characters) unless you set datetime_format on the writer, and it writes default column widths — either way a narrow date column displays as ###. The snippet fixes both: datetime_format="YYYY-MM-DD" for the display format, and three lines to widen the column.

Plan B: hand the DataFrame to Spire.XLS
Plan A is the end of the story when the file just needs to exist. When the workflow extends beyond a basic export — editing cells, applying styles, working with formulas, or converting the workbook to formats such as PDF — Spire.XLS handles those steps through the same standalone API. Spire.XLS is not a pandas ExcelWriter engine — there is no engine="spire" option — so the bridge is df.values.tolist(), which converts the DataFrame into a nested list of Python values that the Spire API writes cell by cell. The snippet reuses the DataFrame defined in Plan A:
from datetime import datetime
import pandas as pd
from spire.xls import Workbook, ExcelVersion, DateTime
header = df.columns.tolist()
data = df.values.tolist()
wb = Workbook()
wb.Worksheets.Clear()
sheet = wb.Worksheets.Add("FromDF")
for j, h in enumerate(header, start=1):
sheet.Range[1, j].Text = str(h)
for i, row in enumerate(data, start=2):
for j, v in enumerate(row, start=1):
cell = sheet.Range[i, j]
if pd.isna(v): # None / NaN / pd.NA / pd.NaT -> empty cell
continue
elif isinstance(v, bool):
cell.BooleanValue = v
elif isinstance(v, datetime): # pd.Timestamp subclasses datetime
cell.DateTimeValue = DateTime.Parse(v.strftime("%Y-%m-%d %H:%M:%S"))
cell.NumberFormat = "yyyy-mm-dd"
elif isinstance(v, (int, float)):
cell.NumberValue = v
else:
cell.Text = str(v)
sheet.AllocatedRange.AutoFitColumns() # widen columns so dates display instead of ###
wb.SaveToFile("output/df_to_spire.xlsx", ExcelVersion.Version2016)
wb.Dispose()
The inner loop is a small type dispatcher, and its branch order is deliberate. The bool check comes before the int check because bool subclasses int in Python — a True would otherwise be written as the number 1. pd.Timestamp subclasses datetime, so that branch catches DataFrame date columns; values go in through DateTime.Parse and carry a NumberFormat, so Excel shows dates rather than serial numbers. pd.isna catches every missing-value marker pandas produces — None, NaN, pd.NA, and pd.NaT — leaving those cells empty. Integers, floats, and booleans keep their types in the saved file. The example handles common scalar values (strings, numbers, booleans, dates, and missing values); other pandas dtypes may need additional conversions.
For workflows that go beyond basic XLSX generation, this is where Spire.XLS earns its place: one standalone API loads existing files, updates values and formulas, applies formatting, manages worksheets, and converts workbooks to formats such as PDF, HTML, or images — all without Microsoft Excel installed. In an automated reporting pipeline, generating the spreadsheet is usually just the first step, and keeping those steps inside one library is what the DataFrame route above sets up.

Write Python Data into XLSX Cells
When the data is a handful of values rather than a table, you write cells directly. The property you assign to decides the cell's type, and this is where the two libraries differ most in day-to-day feel. Each snippet below is self-contained — it creates its own workbook, writes the cells, and saves.
Spire.XLS:
from spire.xls import Workbook, ExcelVersion, DateTime
wb = Workbook()
wb.Worksheets.Clear()
sheet = wb.Worksheets.Add("CellTypes")
sheet.Range["A2"].Text = "Text"
sheet.Range["A3"].Text = "Number"
sheet.Range["A4"].Text = "Date"
sheet.Range["A5"].Text = "Bool"
sheet.Range["A6"].Text = "Formula"
sheet.Range["B2"].Text = "Plain text"
sheet.Range["B3"].NumberValue = 123456.789
sheet.Range["B3"].NumberFormat = "#,##0.00"
sheet.Range["B4"].DateTimeValue = DateTime.Parse("2026-11-17 15:30:00")
sheet.Range["B4"].NumberFormat = "yyyy-mm-dd"
sheet.Range["B5"].BooleanValue = True
sheet.Range["B6"].Formula = "=B3/2"
sheet.AllocatedRange.AutoFitColumns() # so numbers and dates display fully
wb.SaveToFile("output/datatypes_spire.xlsx", ExcelVersion.Version2016)
wb.Dispose()
openpyxl:
from datetime import datetime
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws["A2"] = "Text"
ws["A3"] = "Number"
ws["A4"] = "Date"
ws["A5"] = "Bool"
ws["A6"] = "Formula"
ws["B2"] = "Plain text"
ws["B3"] = 123456.789
ws["B4"] = datetime(2026, 11, 17, 15, 30)
ws["B5"] = True
ws["B6"] = "=B3/2"
ws.column_dimensions["B"].width = 14 # numbers and dates need room to display
wb.save("output/datatypes_openpyxl.xlsx")
Spire.XLS provides dedicated properties for assigning different cell types: Text for strings, NumberValue for numbers, DateTimeValue for dates, BooleanValue for Boolean values, and Formula for formulas. openpyxl, in contrast, infers the cell type from the Python value you assign. A NumberFormat string controls how a value displays, #,##0.00 for the number and yyyy-mm-dd for the date in the example.
One detail saves real debugging time with dates: DateTimeValue takes a Spire DateTime object rather than a Python datetime. Import it alongside the workbook classes (from spire.xls import DateTime) and build one with DateTime.Parse("2026-11-17 15:30:00") or DateTime.get_Now(); the DateTime(year, month, day) constructor form is not available in this package.
Both libraries write formula expressions into cells, but writing a formula is not the same as calculating its result: Excel normally calculates formulas when the workbook is opened with automatic calculation enabled, and openpyxl itself does not calculate them. Spire.XLS can — call wb.CalculateAllValue() before SaveToFile and the cached results land in the file, so downstream readers such as openpyxl with data_only=True can pick them up without opening Excel.
Add a hyperlink (Spire.XLS):
from spire.xls import Workbook, ExcelVersion
wb = Workbook()
wb.Worksheets.Clear()
sheet = wb.Worksheets.Add("Links")
link = sheet.HyperLinks.Add(sheet.Range["A1"]) # note the capital L
link.TextToDisplay = "e-iceblue"
link.Address = "https://www.e-iceblue.com/"
wb.SaveToFile("output/hyperlink_spire.xlsx", ExcelVersion.Version2016)
wb.Dispose()
For a two-dimensional list of rows, openpyxl has a shortcut: ws.append(row) writes one list per row. With Spire.XLS, loop over the rows and reuse the type-dispatch logic from the DataFrame example above, assigning each value to sheet.Range[row, col]. A dedicated walkthrough, including lists of dicts, is in How to Convert Python Lists to Excel (3 Scenarios).

Append Data to an Existing XLSX File
Appending is where straightforward code goes wrong, because of one shared blind spot: openpyxl's ws.max_row and Spire.XLS's sheet.LastRow both report the last row with any cell allocated — including cells that carry formatting but no value. In a workbook whose data ends at row 2 but whose columns are styled down to row 9, both properties return 9. Code that writes to max_row + 1 leaves the new record seven rows below the visible table, inside a band of empty but formatted rows.
The fix is the same in both libraries: pick the column that identifies a record — an order ID, a timestamp, anything present in every data row — and scan it for the last non-empty cell. Both examples below do that, and both tolerate blank rows between records.
Spire.XLS — dynamic append (verified with blank rows and format-only rows in the source file):
from datetime import datetime
from spire.xls import Workbook, DateTime
def append_rows(src, dst, new_rows, key_col=1):
"""Locate the last valid record by scanning the key column,
then write the new rows below it. Skips blank rows and
format-only rows, and tolerates gaps between records.
Row values accept None (leave empty), bool, int/float,
datetime, and strings (converted with str())."""
wb = Workbook()
wb.LoadFromFile(src)
sheet = wb.Worksheets["Data"] # same sheet the openpyxl example reads, by name
last_row = sheet.AllocatedRange.LastRow # includes format-only rows; scan bound only
last_data_row = 1 # header row
r = 2
while r <= last_row:
v = sheet.Range[r, key_col].Value
if v is None or str(v).strip() == "":
has_more = False # an empty key cell doesn't mean no data below
rr = r + 1
while rr <= last_row:
vv = sheet.Range[rr, key_col].Value
if vv is not None and str(vv).strip() != "":
has_more = True
break
rr += 1
if not has_more:
break
r = rr
continue
last_data_row = r
r += 1
for i, row in enumerate(new_rows, start=last_data_row + 1):
for j, v in enumerate(row, start=1):
cell = sheet.Range[i, j]
if v is None:
continue # None -> leave empty
elif isinstance(v, bool):
cell.BooleanValue = v
elif isinstance(v, datetime):
cell.DateTimeValue = DateTime.Parse(v.strftime("%Y-%m-%d %H:%M:%S"))
cell.NumberFormat = "yyyy-mm-dd"
elif isinstance(v, (int, float)):
cell.NumberValue = v
else:
cell.Text = str(v)
wb.SaveToFile(dst)
wb.Dispose()
return last_data_row + len(new_rows)
append_rows("orders.xlsx", "orders_updated.xlsx", [[1005, "Eve", 77.7]])
The function takes a source path, a destination path, and the new rows. It scans the key column from row 2, treating row 1 as the header; AllocatedRange.LastRow serves only as the scan's upper bound precisely because it includes format-only rows. When it meets an empty key cell it keeps looking below, since the data may resume after a gap. New rows are written from last_data_row + 1. Both examples read the sheet by name, so they target the same worksheet even if the source file has more than one. None is left empty, string values are converted with str(), and the remaining values are dispatched to BooleanValue, NumberValue, DateTimeValue, or Text as their types require. The function returns the new last row. On a sheet that has a header and no records yet, the first new record lands in row 2.
openpyxl — the same scan with max_row as the loop bound (verified):
from openpyxl import load_workbook
wb = load_workbook("orders.xlsx")
ws = wb["Data"]
last = 1
for r in range(2, ws.max_row + 1): # max_row counts format-only rows too; don't trust it directly
value = ws.cell(r, 1).value
if value is not None and str(value).strip() != "":
last = r
ws.cell(last + 1, 1, 1005)
ws.cell(last + 1, 2, "Eve")
ws.cell(last + 1, 3, 77.7)
wb.save("orders_updated.xlsx") # separate output file; the input stays untouched
Column 1 is scanned the same way — max_row bounds the loop, and only key cells holding actual content (not blank strings) update last, matching the Spire.XLS logic. Both examples write 1005 / Eve / 77.7 as the next record directly under the existing data, each saving to its own output file.
What pandas mode="a" actually does. pd.ExcelWriter(path, mode="a", engine="openpyxl", if_sheet_exists=...) does not add rows at the end of the sheet — the engine reads the existing workbook and rewrites it entirely. "overlay" keeps the existing sheet and writes the new DataFrame starting at its top-left cell; since a plain to_excel() starts at row 1 with the header, the header and first rows get overwritten. "replace" clears the existing sheet's contents before the new data is written. Content the engine doesn't support, such as charts, can be lost along the way. For adding records below existing data, the key-column scan above is the reliable route.

Format Cells and Manage Multiple Worksheets
Formatting a report usually needs a handful of moves — a styled header, a number format, sensible column widths — plus one more worksheet for the summary. Both libraries cover them. Each snippet below builds a small report from scratch so it can run on its own.
Spire.XLS:
from spire.xls import Workbook, ExcelVersion, Color, HorizontalAlignType
wb = Workbook()
wb.Worksheets.Clear()
sheet = wb.Worksheets.Add("Report")
data = [["Region", "Sales"], ["East", 15000], ["West", 9500]]
for i, row in enumerate(data, start=1):
for j, v in enumerate(row, start=1):
cell = sheet.Range[i, j]
if isinstance(v, (int, float)) and not isinstance(v, bool):
cell.NumberValue = v
else:
cell.Text = str(v)
header = sheet.Range[1, 1, 1, 2] # style A1:B1 in one go
header.Style.Font.IsBold = True
header.Style.Font.Size = 12
header.Style.Color = Color.get_LightGray()
header.Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Range[2, 2, 3, 2].NumberFormat = "$#,##0.00"
sheet.AllocatedRange.AutoFitColumns() # sizes all used columns in one call
# multiple worksheets
summary = wb.Worksheets.Add("Summary")
summary.Range["A1"].Text = "Summary"
wb.SaveToFile("output/format_spire.xlsx", ExcelVersion.Version2016)
wb.Dispose()
The header range A1:B1 is styled in one assignment, and the price cells take a currency NumberFormat. AllocatedRange.AutoFitColumns() sizes all used columns together; the worksheet-level AutoFitColumn() sizes a single column when you need finer control. Conditional formatting, where rules restyle cells when values meet a condition, has its own walkthrough in Apply Various Types of Conditional Formatting to Excel with Python.
openpyxl:
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
wb = Workbook()
ws = wb.active
ws.append(["Region", "Sales"])
ws.append(["East", 15000])
ws.append(["West", 9500])
ws["A1"].font = Font(bold=True, size=12)
ws["A1"].fill = PatternFill("solid", fgColor="D3D3D3")
ws["B2"].number_format = "$#,##0.00"
ws["B3"].number_format = "$#,##0.00"
summary = wb.create_sheet("Summary")
summary["A1"] = "Summary"
wb.save("output/format_openpyxl.xlsx")
The openpyxl counterparts set font and fill on the cell, number_format for display, and create_sheet adds the summary sheet — matching wb.Worksheets.Add("Summary") on the Spire side.
For the complete write API — batch row writing, fonts, borders, backgrounds, and the rest of the object model — the Program Guide goes deeper in Automate Excel Writing in Python.

FAQ
How do I export a pandas DataFrame to an XLSX file?
Call df.to_excel("file.xlsx", index=False) for a single sheet, or write several sheets inside one pd.ExcelWriter context. If the file will need formatting, formulas, or PDF conversion afterwards, convert the DataFrame with df.values.tolist() and write it through Spire.XLS as shown in Plan B of section 2. Spire.XLS is not a pandas ExcelWriter engine, so there is no engine="spire" option.
When I append rows, will existing data be overwritten?
Writing to a fixed cell such as Range["A5"] overwrites whatever is there. Locating the last record by scanning the key column and writing from the next row, as the examples in section 4 do, keeps existing data intact. Note that pandas' mode="a" rewrites the whole workbook, and with if_sheet_exists="overlay" it overwrites the existing sheet starting at its top-left cell, header row included.
Can I write a Python list into an XLSX file?
Yes. With openpyxl, call ws.append(row) once per row. With Spire.XLS, loop over the cells and assign through the typed properties — the dispatch logic is the inner loop of the DataFrame example in section 2. Lists of dicts and other list shapes are covered in the dedicated lists-to-Excel tutorial linked from section 3.
I wrote a formula, but reading the file back gives no value. Why?
Both libraries store the formula string, and the result appears when Excel opens the file. In Spire.XLS, a saved formula carries no cached value by default: call wb.CalculateAllValue() before SaveToFile, and downstream readers such as openpyxl with data_only=True will find the computed value in the file.
How do I write multiple worksheets into one XLSX file?
With openpyxl, call wb.create_sheet("Summary"); with Spire.XLS, call wb.Worksheets.Add("Summary") — and clear the three default sheets of a fresh Spire workbook with wb.Worksheets.Clear() first. With pandas, write inside one ExcelWriter context using different sheet_name values.
Conclusion
Writing an XLSX file in Python is a small set of repeatable moves: create the workbook, write typed values, save — and when the file already exists, find the last record before you write. The examples above cover the versions of those moves you will reach for most often, with the traps that cost debugging time — default sheets, uncached formulas, format-only rows inflating max_row — handled where they occur. When the finished workbook needs to go out as a PDF, Convert Excel to PDF in Python completes the pipeline.
Get a Free 30-Day Trial License
You can request a 30-day temporary license for the full version of Spire.XLS for Python and run these examples without feature limitations: apply for a temporary license.