I'm working on a command-line interface (CLI) script for converting Excel files to CSV. The script uses the argparse library for input handling. If specified, I want to convert all sheets in the Excel file using pandas, and ensure that the output file names are safe and unique. I also need to address how to handle sheet names versus indices, since users may provide either format as command-line arguments. Overall, I'm focused on creating a useful tool!Refining Excel Conversion Logic
I need to add logic to detect if the sheet argument is numeric, so I'll check if it is a digit and convert it to an integer. For handling Excel files, I want to ensure the file exists with an os.path.isfile check. When it comes to dependencies, I'll mention installing them via pip—users will need pandas, openpyxl, and xlrd. Since xlrd no longer supports .xlsx, it’s important to clarify that if users need .xls, they should install xlrd==1.2.0. I want to keep these notes concise for clarity!Creating Python Script for Excel Conversion
Pandas is a robust tool for this task, so I'll proceed with a Python script as outlined. Since the user may be on Windows, I need to consider potential path issues. I’ll provide a clear layout for the response, starting with a brief description followed by dependencies and installation.
Next, I’ll include the complete script for excel_to_csv.py, with usage examples such as converting the first sheet and specifying sheets by name or index. I'll also mention that the generated CSV files will use UTF-8 encoding and have no index column to customize it for the user!Adding Disclaimers and Error Handling
I realize I need to include disclaimers regarding large files, as users might face memory issues. While edge cases like line encoding are important, the default is already set to newline \n. I’ll set the encoding explicitly for clarity, using df.to_csv(csv_path, index=False, encoding='utf-8').
Next, I want to ensure safe sheet names are sanitized for file naming and implement a simple sanitize_sheet_name function. Minimal error handling is essential, so I’ll include checks for file existence and use a try/except block for exceptions while keeping it straightforward. Don't forget the shebang at the top for Unix execution! Use pandas to read Excel and write CSV. Below is a complete CLI script that can:
Convert a single sheet or all sheets
Handle .xlsx (and .xls if you install xlrd)
1. Install dependencies
bash
pip install pandas openpyxl
# For old .xls files (optional):
pip install "xlrd==1.2.0"
2. Script: excel_to_csv.py
python
3. Usage
From the directory containing excel_to_csv.py:
bash
# Convert first sheet to CSV
python excel_to_csv.py myfile.xlsx
# Convert a specific sheet by name
python excel_to_csv.py myfile.xlsx --sheet "Sheet2"
# Convert a specific sheet by index (0-based)
python excel_to_csv.py myfile.xlsx --sheet 1
# Convert all sheets to separate CSV files
python excel_to_csv.py myfile.xlsx --all-sheets
# Choose output directory
python excel_to_csv.py myfile.xlsx --all-sheets -o ./csv_output
If you want changes (e.g., always using a specific delimiter, including the index column, or handling very large files), say what you need and I can adjust the script.
#!/usr/bin/env python3
"""
Convert Excel spreadsheets (.xlsx, .xls) to CSV.
Usage examples:
python excel_to_csv.py workbook.xlsx
python excel_to_csv.py workbook.xlsx --sheet Sheet2
python excel_to_csv.py workbook.xlsx --sheet 1
python excel_to_csv.py workbook.xlsx --all-sheets
python excel_to_csv.py workbook.xlsx -o output_dir --all-sheets
"""
import argparse
import os
import sys
import pandas as pd
def sanitize_name(name: str) -> str:
"""Make a safe filename from a sheet name."""
valid = "-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
cleaned = "".join(c if c in valid else "_" for c in str(name)).strip()
return cleaned or "sheet"
def excel_to_csv(excel_path: str, output_dir: str | None, sheet, all_sheets: bool):
if not os.path.isfile(excel_path):
print(f"Error: file not found: {excel_path}", file=sys.stderr)
sys.exit(1)
if output_dir is None:
output_dir = os.path.dirname(os.path.abspath(excel_path)) or "."
os.makedirs(output_dir, exist_ok=True)
base = os.path.splitext(os.path.basename(excel_path))[0]
if all_sheets:
xls = pd.ExcelFile(excel_path)
for sheet_name in xls.sheet_names:
df = pd.read_excel(xls, sheet_name=sheet_name)
safe = sanitize_name(sheet_name)
csv_name = f"{base}__{safe}.csv"
csv_path = os.path.join(output_dir, csv_name)
df.to_csv(csv_path, index=False, encoding="utf-8")
print(f"Wrote {csv_path}")
else:
df = pd.read_excel(excel_path, sheet_name=sheet)
suffix = ""
if sheet is not None:
# Use original sheet identifier (name or index) in filename
suffix = f"__{sanitize_name(sheet)}"
csv_name = f"{base}{suffix}.csv"
csv_path = os.path.join(output_dir, csv_name)
df.to_csv(csv_path, index=False, encoding="utf-8")
print(f"Wrote {csv_path}")
def parse_args():
parser = argparse.ArgumentParser(
description="Convert Excel (.xlsx, .xls) files to CSV."
)
parser.add_argument("excel_file", help="Path to the input Excel file")
parser.add_argument(
"-o",
"--output-dir",
help="Directory to write CSV file(s) to (default: same as input file)",
default=None,
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-s",
"--sheet",
help="Sheet name or 0-based index to convert (default: first sheet)",
)
group.add_argument(
"-a",
"--all-sheets",
help="Convert all sheets to separate CSV files",
action="store_true",
)
args = parser.parse_args()
# If sheet looks like an integer, treat it as an index
sheet = args.sheet
if sheet is not None:
try:
sheet_int = int(sheet)
sheet = sheet_int
except ValueError:
pass # keep as string (sheet name)
return args, sheet
def main():
args, sheet = parse_args()
try:
excel_to_csv(
excel_path=args.excel_file,
output_dir=args.output_dir,
sheet=sheet,
all_sheets=args.all_sheets,
)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()