The user wants a Python script to convert Excel spreadsheets (usually .xlsx or .xls) to CSV format.
Key Requirements:
- Input: An Excel file (path provided by the user).
- Output: One or more CSV files (since an Excel workbook can have multiple sheets).
- Language: Python.
- Library: The standard library for data manipulation in Python is
pandas. It's robust and handles this specific task very well. Another option is openpyxl, but pandas is generally easier for this specific "convert and dump" operation.
Design Decisions:
Drafting the Code (Mental or Scratchpad):
- Import:
import pandas as pd, import os, import sys.
- Function:
excel_to_csv(excel_file, output_dir).
- Logic:
- Read Excel:
xls = pd.ExcelFile(excel_file).
- Loop through sheet names:
for sheet_name in xls.sheet_names:.
- Read specific sheet:
df = pd.read_excel(xls, sheet_name).
- Construct output filename:
base_name + "_" + sheet_name + ".csv". Need to clean sheet names (remove invalid characters).
- Save:
df.to_csv(output_path, index=False).
Refining the Script:
- Make it a command-line tool? Yes, using
argparse makes it professional and reusable.
- Add comments and docstrings.
- Include a
requirements.txt instruction since pandas and openpyxl (dependency for reading xlsx) are external.
Step-by-Step Plan:
- Prerequisites: Mention
pandas and openpyxl.
- The Script:
- Import libraries.
- Define a function that takes the input file and output folder.
- Use Pandas to read the Excel file.
- Iterate through sheets.
- Save each sheet as a CSV.
- Add a
main block to handle command-line arguments.
- Usage: Explain how to run it from the terminal.
Alternative (Lightweight) Approach:
If the user doesn't want to install Pandas (which is heavy), I could use the csv and openpyxl libraries directly. However, Pandas handles edge cases (dates, numbers, mixed types) much better. I will stick with Pandas as the primary recommendation but maybe acknowledge the library requirement.
Code Structure:
import pandas as pd
import os
import sys
def convert_excel_to_csv(input_file, output_dir=None):
# ... logic ...
Edge Case Handling:
- What if the sheet name contains characters invalid for filenames? (Replace them).
- What if the output directory doesn't exist? (Create it).
Final Polish:
Ensure the CSV uses index=False so row numbers aren't written to the file.
Let's write the response. I will provide a robust script using pandas because it's the industry standard. I will also include instructions on how to install dependencies.
Self-Correction during drafting:
I initially thought about just converting the active sheet. But usually, when people ask for this, they want the data, and splitting multi-sheet workbooks into multiple CSVs is the safest approach to data integrity.
Dependencies:
pip install pandas openpyxl (openpyxl is the engine pandas uses for .xlsx).
Constructing the response:
- Installation: Command to install packages.
- The Code: Complete, copy-pasteable script.
- How to use: Command line examples.
- Explanation: Briefly explain what the code does (handling multiple sheets).
Let's build the code now.
import pandas as pd
import os
import re
def sanitize_filename(name):
# Remove invalid characters
return re.sub(r'[\\/*?:"<>|]', "", name)
def excel_to_csv(input_path, output_folder="."):
try:
# Read the Excel file
xls = pd.ExcelFile(input_path)
# Get the file name without extension
base_name = os.path.splitext(os.path.basename(input_path))[0]
print(f"Found {len(xls.sheet_names)} sheet(s): {xls.sheet_names}")
for sheet_name in xls.sheet_names:
# Read specific sheet
df = pd.read_excel(xls, sheet_name=sheet_name)
# Construct output filename
clean_sheet_name = sanitize_filename(sheet_name)
if len(xls.sheet_names) > 1:
csv_filename = f"{base_name}_{clean_sheet_name}.csv"
else:
csv_filename = f"{base_name}.csv"
output_path = os.path.join(output_folder, csv_filename)
# Save to CSV
df.to_csv(output_path, index=False, encoding='utf-8')
print(f"Saved: {output_path}")
except Exception as e:
print(f"Error: {e}")
# ... add argparse boilerplate ...
This looks solid. I will present this clearly.
One small detail: Windows paths. os.path handles this well.
One small detail: Encoding. utf-8 is standard, but sometimes Excel has weird encodings. Pandas handles this well usually, but sticking to utf-8 for output is the modern standard.
I will provide two versions:
- A simple function-based script (easy to read).
- A command-line ready script (using
argparse).
Actually, a single robust script with argparse is best. It covers both usage styles (can be imported as a module or run as a script).
Let's finalize the response structure.
- Prerequisites (
pip install).
- The Python Script.
- Usage instructions.
- Key features explanation (multi-sheet handling, sanitizing filenames).
Wait, the prompt is simple: "Build a Python script". I shouldn't over-engineer it, but it should be robust. I'll stick to the Pandas approach.
Check: openpyxl is needed for .xlsx. xlrd is needed for older .xls (though pandas deprecated xlrd for xlsx, it might still be needed for xls). Pandas usually defaults to openpyxl for xlsx now. I will add openpyxl to the install command.
Code Check:
pd.read_excel(input_path, sheet_name=None) reads all sheets into a dictionary. This might be slightly cleaner than ExcelFile object loop, but ExcelFile is slightly more memory efficient if dumping immediately. Actually, sheet_name=None returns a dict {sheet_name: dataframe}. This is very pythonic.
Let's use the dictionary approach:
dfs = pd.read_excel('file.xlsx', sheet_name=None)
for name, df in dfs.items():
# save
This is concise.
Final Plan:
- Dependencies:
pandas, openpyxl.
- Script:
- Import
pandas, os, sys (for args).
- Function
convert_excel_to_csv.
- Handle output directory creation.
- Handle multi-sheet logic (e.g.,
File_SheetName.csv).
if __name__ == "__main__": block to take file path as argument.
This covers all bases.
Here is a robust Python script to convert Excel files (.xlsx, .xls) to CSV format.
Prerequisites
You will need the pandas library (for data manipulation) and openpyxl (to read modern Excel files). You can install them via pip:
pip install pandas openpyxl
The Python Script
Save this code as excel_to_csv.py.
This script handles multiple sheets automatically. If your Excel file has 3 sheets, it will create 3 CSV files (named filename_SheetName.csv).
import pandas as pd
import os
import sys
import re
def sanitize_filename(name):
"""
Removes characters that are invalid in file names
and replaces spaces with underscores.
"""
# Replace spaces with underscores
name = name.replace(" ", "_")
# Remove invalid characters (like \ / : * ? " < > |)
name = re.sub(r'[\\/*?:"<>|]', "", name)
return name
def convert_excel_to_csv(excel_path, output_dir=None):
"""
Reads an Excel file and converts all sheets to separate CSV files.
"""
# Check if file exists
if not os.path.exists(excel_path):
print(f"Error: The file '{excel_path}' does not exist.")
return
# Determine output directory
if output_dir is None:
# Default to the same directory as the Excel file
output_dir = os.path.dirname(excel_path)
if not output_dir:
output_dir = os.getcwd() # Use current working dir if no path provided
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
try:
# Read the Excel file
# sheet_name=None reads ALL sheets into a dictionary of DataFrames
print(f"Reading file: {excel_path}...")
xls = pd.ExcelFile(excel_path)
# Get the base filename without extension
base_filename = os.path.splitext(os.path.basename(excel_path))[0]
sheet_count = 0
# Iterate through each sheet
for sheet_name in xls.sheet_names:
# Read specific sheet into DataFrame
df = pd.read_excel(xls, sheet_name=sheet_name)
# Construct output filename
# Format: OriginalName_SheetName.csv
clean_sheet_name = sanitize_filename(sheet_name)
if len(xls.sheet_names) > 1:
csv_filename = f"{base_filename}_{clean_sheet_name}.csv"
else:
csv_filename = f"{base_filename}.csv"
output_path = os.path.join(output_dir, csv_filename)
# Save to CSV
# index=False prevents pandas from writing row numbers (0,1,2...)
df.to_csv(output_path, index=False, encoding='utf-8')
print(f"Successfully converted sheet '{sheet_name}' -> {output_path}")
sheet_count += 1
print(f"\nDone! {sheet_count} file(s) generated.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Command Line Interface Logic
if len(sys.argv) < 2:
print("Usage: python excel_to_csv.py <excel_file_path> [output_directory]")
print("Example: python excel_to_csv.py data.xlsx output_folder/")
sys.exit(1)
input_file = sys.argv[1]
output_folder = sys.argv[2] if len(sys.argv) > 2 else None
convert_excel_to_csv(input_file, output_folder)
How to use it
1. Basic usage (Same folder):
This will create data_Sheet1.csv inside the current folder.
python excel_to_csv.py data.xlsx
2. Specify output folder:
This will create the CSV files inside a folder named csv_output.
python excel_to_csv.py data.xlsx csv_output
3. Drag and Drop:
You can also drag and drop an Excel file directly onto the script file (in Windows), and it will convert the file in the same location.
Key Features of this Script:
- Multi-Sheet Support: Unlike simple scripts that only read the first tab, this reads all sheets in the workbook. If a file has multiple sheets, it appends the sheet name to the filename (e.g.,
Budget_Q1.csv, Budget_Q2.csv).
- No Index Column: It uses
index=False so your CSV doesn't contain an extra column of row numbers.
- Sanitization: It automatically removes illegal characters (like
/, :, *) from sheet names to prevent file creation errors.
- Encoding: It uses
utf-8 to ensure special characters and emojis are preserved.