How to Convert Excel to CSV using Python
In this tutorial, you will convert an Excel file to a CSV file using Python and `pandas.
TLDR solution
excel2csv.py
import pandas as pd
df = pd.read_excel("path-to-file/file_name.xlsx", sheet_name="SheetName")
df.to_csv("target-path/file_name.csv", index=False, header=True)
Step-by-Step Example
Step 1: Install the pandas and openpyxl
If you don't have the packages pandas and openpyxl already installed, execute the following command in your terminal:
pip install pandas openpyxl
Note that we will use the pandas function read_excel below which depends on openpyxl.
Step 2: Import an Excel File and Export as CSV
Let's say, you have an excel file named fish.xlsx on your desktop.
Create a Python script that loads the Excel file into a DataFrame and exports it as a CSV file:
excel2csv.py
import os
import pandas as pd
desktop_path = os.path.expanduser("~/Desktop")
df = pd.read_excel(desktop_path + "/fish.xlsx", sheet_name="Sheet1")
df.to_csv(desktop_path + "/fish.csv", index=False, header=True)
After you run this code, you will find a fish.csv file on your desktop.
That's it! You just learned how to convert an Excel file to a CSV file using Python and pandas.