To export a pandas DataFrame to Excel, use the to_excel() method: df.to_excel('output.xlsx', index=False). This writes the DataFrame to an .xlsx file in your current working directory. For more control—such as multiple sheets or formatting—use pd.ExcelWriter with a compatible engine like openpyxl. Below is a complete guide covering setup, step-by-step instructions, common pitfalls, and troubleshooting.
What You'll Need
- Python 3.7 or later installed on your system.
- pandas library installed (
pip install pandas). - An Excel writer engine: openpyxl for .xlsx files (
pip install openpyxl) or xlsxwriter for advanced formatting (pip install xlsxwriter). For .xls files, use xlwt (pip install xlwt), though .xls is legacy and not recommended. - A DataFrame loaded in your Python script or Jupyter notebook.
Step-by-Step
- Import pandas and create or load your DataFrame. For example:
import pandas as pd df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Score': [85, 92]}) - Choose your output file path. Decide where to save the file, e.g.,
'output.xlsx'for the current directory or an absolute path like'/home/user/reports/data.xlsx'. Ensure the directory exists and you have write permissions. - Call
to_excel()with basic parameters. The simplest export:
Settingdf.to_excel('output.xlsx', index=False)index=Falseprevents pandas from writing the DataFrame index as an extra column. Omit it if you want the index included. - For multiple sheets, use
ExcelWriter. Create a writer object and write each DataFrame to a sheet:
Thewith pd.ExcelWriter('output.xlsx', engine='openpyxl') as writer: df.to_excel(writer, sheet_name='Sheet1', index=False) df2.to_excel(writer, sheet_name='Sheet2', index=False)withstatement ensures the file is properly saved and closed. - Apply formatting (optional). If you need column widths, bold headers, or number formats, use xlsxwriter as the engine and access its workbook and worksheet objects:
Note that xlsxwriter does not support reading or modifying existing files; it only writes new ones.with pd.ExcelWriter('output.xlsx', engine='xlsxwriter') as writer: df.to_excel(writer, sheet_name='Sheet1', index=False) workbook = writer.book worksheet = writer.sheets['Sheet1'] worksheet.set_column('A:B', 20) # set column widths - Verify the file. Open the generated .xlsx file in Excel, LibreOffice Calc, or another spreadsheet program to confirm the data and formatting are correct.
Common Mistakes
- Forgetting to install an engine. pandas requires openpyxl (or another engine) for .xlsx files. Without it, you'll get an ImportError.
- Not setting
index=False. This writes the row numbers as a column, which is often unwanted. - Overwriting an existing file without warning.
to_excel()will overwrite the target file silently. Double-check the filename. - Using the wrong engine for the file extension. For example, using xlsxwriter for .xls files will fail. Match engine to extension.
- Assuming xlsxwriter can append to existing files. It cannot; use openpyxl in append mode if you need to add sheets to an existing workbook.
- Ignoring datetime or special characters. Excel may misinterpret dates or encoding; specify
date_formator ensure UTF-8 if needed.
Tips
- Use
index=Falseunless you specifically need the index in the output. - For large DataFrames, consider writing to .xlsx with openpyxl; it handles large files reasonably well. Avoid .xls for large data due to row limits.
- If you need to preserve existing formatting in a template, use openpyxl with
mode='a'(append) andif_sheet_exists='overlay'(available in pandas 1.3+). - Always use a context manager (
with) when usingExcelWriterto ensure the file is saved and closed properly. - Test your export with a small sample first to catch issues early.
Troubleshooting
If the export fails or the file is not as expected, try these steps in order:
- Check for missing dependencies. Run
pip install openpyxlorpip install xlsxwriteras needed. Restart your Python kernel after installation. - Verify the file path and permissions. Ensure the directory exists and you have write access. Use an absolute path to avoid confusion.
- Look at the error message. Common errors include
ModuleNotFoundError(missing engine),PermissionError(file open in Excel), orValueError(invalid sheet name). - Close the file if it's open in Excel. Excel locks files; close it before writing.
- Try a different engine. If openpyxl fails, try xlsxwriter (for writing only) or vice versa.
- Check for unsupported data types. Objects like lists or dicts in cells may cause errors; convert them to strings first.
- Update pandas and the engine. Older versions may have bugs; upgrade with
pip install --upgrade pandas openpyxl.
If it still does not work, simplify: export a tiny DataFrame to a new file in a simple path (e.g., 'test.xlsx' in your home directory) to isolate the problem.
Frequently Asked Questions
Can I export multiple DataFrames to one Excel file?
Yes, use pd.ExcelWriter and write each DataFrame to a different sheet name.
How do I export without the index column?
Pass index=False to to_excel().
What is the difference between openpyxl and xlsxwriter?
openpyxl can read and write .xlsx files and supports appending to existing files; xlsxwriter is write-only but offers more formatting options. Choose based on your needs.
Can I export to .xls (old format)?
Yes, but you need the xlwt engine (pip install xlwt). However, .xls is limited and not recommended; use .xlsx instead.
Why do I get a “No module named 'openpyxl'” error?
You haven't installed openpyxl. Run pip install openpyxl in your terminal or command prompt.
How do I format dates or numbers in the Excel output?
Use the date_format parameter in to_excel() for dates, or apply formatting via the engine's API (e.g., xlsxwriter's set_column with a format object).