Export Pandas DataFrame to an Excel File

You can export Pandas DataFrame to an Excel file using to_excel:

df.to_excel(r"Path to store the Excel\File Name.xlsx", index=False)

And if you want to export your DataFrame to a specific Excel Sheet:

df.to_excel(r"Path to store the Excel\File Name.xlsx", sheet_name="Your sheet name", index=False)

Note: you’ll have to install openpyxl if you get the following error:

ModuleNotFoundError: No module named ‘openpyxl’

You can install openpyxl using this command:

pip install openpyxl

The Example

Let’s say that you have the following dataset about products and their prices:

product_nameprice
computer1200
printer150
tablet300
monitor450

The ultimate goal is to export that dataset into Excel.

To start, create a DataFrame in order to capture the above data in Python:

import pandas as pd

data = {
"product_name": ["computer", "printer", "tablet", "monitor"],
"price": [1200, 150, 300, 450],
}

df = pd.DataFrame(data)

print(df)

This is how the DataFrame would look like:

  product_name  price
0     computer   1200
1      printer    150
2       tablet    300
3      monitor    450

Next, define the path where you’d like to store the exported Excel file.

For example, the path below will be used to store the exported Excel file (note that you’ll need to adjust the path to reflect the location where the Excel file will be stored on your computer):

r“C:\Users\Ron\Desktop\my_products.xlsx

Notice that 3 components were highlighted in relation to that path:

  • In yellow, the ‘r‘ character is placed before the path to avoid any unicode errors
  • In blue, the file name to be created is specified. You may specify a different file name based on your needs
  • In green, the file type is specified. Since we are dealing with an Excel file, the file type would be ‘.xlsx‘ for the latest version of Excel

Putting everything together, here is the full Python code to export the DataFrame to an Excel file:

import pandas as pd

data = {
"product_name": ["computer", "printer", "tablet", "monitor"],
"price": [1200, 150, 300, 450],
}

df = pd.DataFrame(data)

df.to_excel(r"C:\Users\Ron\Desktop\my_products.xlsx", index=False)

Finally, run the above code in Python (adjusted to your path), and you’ll notice that a new Excel file (called my_products) would be created at the location that you specified.

Note that if you wish to include the index, then simply remove “, index=False” from the code.

Additional Resources

You just saw how to export Pandas DataFrame to an Excel file. At times, you may need to export Pandas DataFrame to a CSV file. The concept would be similar in such cases.

You may also want to check the Pandas Documentation for additional information about df.to_excel.

Leave a Comment