#!/usr/bin/env python3
"""
Excel to CSV Converter
=====================
A simple Python script to convert Excel spreadsheets (.xlsx, .xls) to CSV format.
Requirements:
- Python 3.x
- pandas (pip install pandas openpyxl)
- openpyxl is needed for .xlsx files
Usage:
python excel_to_csv.py input.xlsx [-o output.csv] [-s Sheet1] [--all-sheets]
Options:
input.xlsx Path to the input Excel file (required)
-o, --output Output CSV file path (optional; defaults to input stem + .csv)
-s, --sheet Sheet name or index (default: 0, first sheet)
--all-sheets Convert all sheets to separate CSV files (ignores --sheet)
Examples:
python excel_to_csv.py data.xlsx
python excel_to_csv.py data.xlsx -o output.csv -s "Sheet2"
python excel_to_csv.py data.xlsx --all-sheets
"""
import argparse
import os
import sys
from pathlib import Path
import pandas as pd
def convert_excel_to_csv(input_path: str, output_path: str = None, sheet_name: str = 0):
"""Convert a single sheet from Excel to CSV."""
try:
df = pd.read_excel(input_path, sheet_name=sheet_name)
df.to_csv(output_path, index=False)
print(f"✓ Converted '{sheet_name}' from '{input_path}' to '{output_path}'")
return True
except Exception as e:
print(f"✗ Error converting '{sheet_name}' from '{input_path}': {e}", file=sys.stderr)
return False
def convert_all_sheets(input_path: str, output_dir: str = None):
"""Convert all sheets from Excel to separate CSVs."""
try:
excel_file = pd.ExcelFile(input_path)
input_stem = Path(input_path).stem
output_dir = Path(output_dir or input_stem)
output_dir.mkdir(exist_ok=True)
success_count = 0
for sheet_name in excel_file.sheet_names:
output_path = output_dir / f"{input_stem}_{sheet_name}.csv"
if convert_excel_to_csv(input_path, str(output_path), sheet_name):
success_count += 1
print(f"✓ Processed {success_count}/{len(excel_file.sheet_names)} sheets from '{input_path}' to '{output_dir}'")
return success_count > 0
except Exception as e:
print(f"✗ Error processing all sheets from '{input_path}': {e}", file=sys.stderr)
return False
def main():
parser = argparse.ArgumentParser(
description="Convert Excel spreadsheets to CSV",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s data.xlsx
%(prog)s data.xlsx -o output.csv -s "Sheet2"
%(prog)s data.xlsx --all-sheets
"""
)
parser.add_argument("input", help="Input Excel file (.xlsx or .xls)")
parser.add_argument("-o", "--output", help="Output CSV file (ignored with --all-sheets)")
parser.add_argument("-s", "--sheet", default=0, help="Sheet name or index (default: 0)")
parser.add_argument("--all-sheets", action="store_true", help="Convert all sheets to separate CSVs")
args = parser.parse_args()
input_path = Path(args.input)
if not input_path.exists():
print(f"✗ Input file '{input_path}' not found.", file=sys.stderr)
sys.exit(1)
if not input_path.suffix.lower() in {".xlsx", ".xls", ".xlsm"}:
print(f"✗ '{input_path}' is not a supported Excel file (.xlsx, .xls, .xlsm).", file=sys.stderr)
sys.exit(1)
if args.all_sheets:
success = convert_all_sheets(str(input_path), args.output)
else:
if not args.output:
stem = input_path.stem
args.output = f"{stem}.csv"
success = convert_excel_to_csv(str(input_path), args.output, args.sheet)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
How to Use
-
Install dependencies:
pip install pandas openpyxl
-
Save the script as excel_to_csv.py and make it executable (optional):
chmod +x excel_to_csv.py
-
Run examples:
# Convert first sheet to data.csv
python excel_to_csv.py data.xlsx
# Convert specific sheet
python excel_to_csv.py data.xlsx -o output.csv -s "MySheet"
# Convert all sheets to separate CSVs in a folder
python excel_to_csv.py data.xlsx --all-sheets
Features
- Single sheet or all sheets conversion.
- Automatic output naming if not specified.
- Error handling for invalid files/sheets.
- Supports .xlsx, .xls, .xlsm.
- No index column in CSV output (common preference).
- Cross-platform (uses
pathlib).
This script is production-ready and handles edge cases gracefully! 🚀