HOWTO · Python
How to Write to an Excel Spreadsheet in Python
Learn how to write tabular data and individual cells to an .xlsx workbook in Python with pandas and openpyxl, and how to verify the exported file.
On this page
Python can write an Excel workbook from a pandas DataFrame or by assigning individual cells with openpyxl. Use pandas for tabular exports, openpyxl for workbook-level control, and XlsxWriter when you need rich formatting in a new workbook.
Write a DataFrame to an .xlsx File With pandas
The simplest way to write a table is the pandas DataFrame.to_excel() method. It creates an .xlsx file, writes the column names and rows, and lets you choose the worksheet name.
The following example writes a small table and reads it back to verify the saved values. Install pandas and an Excel engine such as openpyxl before running it.
import pandas as pd
sales = pd.DataFrame({"Product": ["Notebook", "Pen"], "Units": [3, 8]})
sales.to_excel("sales.xlsx", sheet_name="Sales", index=False)
saved = pd.read_excel("sales.xlsx", sheet_name="Sales")
print(saved.to_dict(orient="records"))
The output is [{'Product': 'Notebook', 'Units': 3}, {'Product': 'Pen', 'Units': 8}]. Set index=False when the DataFrame index is not a data column. If you build the DataFrame from separate lists, make sure the lists have equal lengths.
Write Multiple Sheets With ExcelWriter
Use pd.ExcelWriter when one workbook needs several tables. Write each DataFrame to the same writer with a different sheet_name, then let the context manager close the workbook.
import pandas as pd
sales = pd.DataFrame({"Product": ["Notebook", "Pen"], "Units": [3, 8]})
returns = pd.DataFrame({"Product": ["Pen"], "Units": [1]})
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
sales.to_excel(writer, sheet_name="Sales", index=False)
returns.to_excel(writer, sheet_name="Returns", index=False)
print(pd.ExcelFile("report.xlsx").sheet_names)
The output is ['Sales', 'Returns']. A context manager is useful here because it closes the writer even when the surrounding code grows to include more export steps.
Write Cells With openpyxl
Use openpyxl when the input is not already a DataFrame or when you need direct access to worksheets and cells. Assign a cell by coordinate, append rows, and save the workbook when the edits are complete.
from openpyxl import Workbook, load_workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = "Summary"
sheet["A1"] = "Product"
sheet["B1"] = "Units"
sheet.append(["Notebook", 3])
workbook.save("summary.xlsx")
saved = load_workbook("summary.xlsx", data_only=True)
print(saved["Summary"]["A2"].value, saved["Summary"]["B2"].value)
The output is Notebook 3. The cell(row, column) method is another option when row and column numbers are easier to calculate than Excel coordinates.
Choose pandas, openpyxl, or XlsxWriter
Choose pandas when the source is tabular data and you want a short export path. Choose openpyxl when you must edit existing workbooks or address cells, formulas, and worksheets directly. Both approaches can produce the modern .xlsx format.
XlsxWriter is useful for creating a new, formatting-heavy workbook. Unlike openpyxl, it is focused on writing rather than editing an existing workbook. The older xlwt approach targets legacy .xls files and should be reserved for a system that explicitly requires that format.
Keep the file extension consistent with the library and engine. In particular, do not save an .xlsx workbook with an .xls extension or assume that a writer can edit a workbook after it has been closed.
Verify the Workbook and Handle Common Failures
After writing, check that the expected path exists and that the workbook can be opened. A missing output usually means the export step did not run, failed before saving, or wrote to a different working directory.
from pathlib import Path
output = Path("missing.xlsx")
if not output.exists():
raise FileNotFoundError(f"Expected export was not created: {output}")
print(output.suffix, output.stat().st_size > 0)
This boundary check raises FileNotFoundError until an export creates missing.xlsx; it prevents later code from silently consuming a missing file. Also verify worksheet names and representative cell values when the workbook is part of an automated pipeline.