Convert Excel Worksheets to CSV Files Using Python

By Farhad Uddin . · 4 min read

Working with Excel files is a common task for data analysts, developers, and business professionals. But sometimes, you need to convert Excel worksheets into CSV format — a lightweight, widely supported format for storing tabular data. In this blog post, we'll show you how to use Python to automatically convert Excel worksheets into CSV files, including handling multi-sheet Excel files.


Why Convert Excel to CSV?


  1. CSV files are lightweight and easy to process.
  2. CSV format is compatible with many tools (databases, analytics platforms, web apps).
  3. Automating conversion saves time, especially when dealing with large or recurring datasets.



Step 1: Install Python

First, ensure Python is installed on your system.

For Windows/macOS/Linux:

Download Python from the official website:

https://www.python.org/downloads/

Then verify the installation:


c:\user\username> python --version
Python 3.11.9


Step 2: Install Required Dependencies

We will use the pandas openpyxl library to manipulate Excel files while maintaining full formatting.

Open your terminal or command prompt and run:


c:\user\username> pip install pandas openpyxl


Tip: You can also create a virtual environment for better project management.


python -m venv env
source env/bin/activate # On Windows: env\Scripts\activate
pip install pandas openpyxl


Step 3: Prepare Your Excel File

Here’s a full script to export each worksheet as a separate Excel file:


import os
import pandas as pd

folder_path = "./excel_files"

for file in os.listdir(folder_path):
if file.endswith(".xlsx") or file.endswith(".xls"):
file_path = os.path.join(folder_path, file)
excel = pd.ExcelFile(file_path)
for sheet in excel.sheet_names:
df = excel.parse(sheet)
csv_name = f"{os.path.splitext(file)[0]}_{sheet}.csv"
csv_path = os.path.join(folder_path, csv_name)
df.to_csv(csv_path, index=False)
print(f"Saved: {csv_path}")


Using Python to convert Excel worksheets to CSV files is a simple but powerful way to automate data processing. With just a few lines of code, you can handle large Excel files, multiple sheets, and even batch-process entire folders.

Tags: python flask
Author

Farhad Uddin

Blogger