Write Excel with Pandas

In addition to reading spreadsheets, Pandas can easily export any DataFrame directly to an Excel file using the to_excel() method.

Writing a DataFrame to Excel

You can create a DataFrame from Python dictionaries or lists, and save it to an .xlsx file:

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Berlin']
}

df = pd.DataFrame(data)

# Export DataFrame to Excel
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)
print("Saved to output.xlsx")

Writing Multiple Sheets with ExcelWriter

To write multiple DataFrames to distinct sheets within the same Excel workbook, use pd.ExcelWriter:

import pandas as pd

df1 = pd.DataFrame({'Data': [1, 2, 3]})
df2 = pd.DataFrame({'Scores': [90, 85, 95]})

with pd.ExcelWriter('multiple_sheets.xlsx') as writer:
    df1.to_excel(writer, sheet_name='Sheet1', index=False)
    df2.to_excel(writer, sheet_name='Sheet2', index=False)
Back ⚡ Practice with PyChallengeNext