We use to_excel to save data from a table (DataFrame) into an Excel file. This helps share or keep data in a common, easy-to-open format.
Writing to Excel with to_excel in Pandas
DataFrame.to_excel(excel_writer, sheet_name='Sheet1', index=True, header=True)
excel_writer is the file path or Excel writer object where data will be saved.
sheet_name sets the name of the Excel sheet (default is 'Sheet1').
df to an Excel file named output.xlsx with default sheet name and index included.df.to_excel('output.xlsx')df to output.xlsx with sheet named 'Data' and without row index numbers.df.to_excel('output.xlsx', sheet_name='Data', index=False)
df without column headers in the Excel file.df.to_excel('output.xlsx', header=False)
This program creates a small table with names and ages, saves it to an Excel file named people.xlsx on a sheet called 'PeopleData', without row indexes. Then it reads the file back and prints it to confirm the data saved correctly.
import pandas as pd # Create a simple DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) # Save DataFrame to Excel file df.to_excel('people.xlsx', sheet_name='PeopleData', index=False) # Read back the file to check df_check = pd.read_excel('people.xlsx', sheet_name='PeopleData') print(df_check)
If you do not want to save the row numbers, set index=False.
You need to have the openpyxl package installed to write Excel files (.xlsx).
By default, column headers are saved. Use header=False to skip them.
to_excel saves your DataFrame as an Excel file for easy sharing and storage.
You can choose the sheet name, and whether to include row indexes and headers.
Make sure to install openpyxl to work with Excel files in pandas.