Created
October 15, 2024 19:44
-
-
Save jatinkrmalik/721997cbdb37b309e224b263f732a271 to your computer and use it in GitHub Desktop.
excel_to_csv.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install pandas openpyxl | |
import sys | |
import pandas as pd | |
def excel_to_csv(excel_file_path, sheet_name=0, csv_file_path=None): | |
# Read the Excel file | |
try: | |
df = pd.read_excel(excel_file_path, sheet_name=sheet_name) | |
except Exception as e: | |
print(f"Error reading the Excel file: {e}") | |
sys.exit(1) | |
# If no CSV file path is provided, use the Excel file name with .csv extension | |
if csv_file_path is None: | |
csv_file_path = excel_file_path.rsplit('.', 1)[0] + '.csv' | |
# Write the DataFrame to a CSV file | |
try: | |
df.to_csv(csv_file_path, index=False) | |
print(f"Excel file '{excel_file_path}' has been converted to CSV file '{csv_file_path}'.") | |
except Exception as e: | |
print(f"Error writing the CSV file: {e}") | |
sys.exit(1) | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
print("Usage: python excel_to_csv.py <excel_file_path> [<csv_file_path>]") | |
sys.exit(1) | |
excel_file_path = sys.argv[1] | |
csv_file_path = sys.argv[2] if len(sys.argv) > 2 else None | |
excel_to_csv(excel_file_path, csv_file_path=csv_file_path) | |
# Usage | |
# Save this script as excel_to_csv.py and run it from the command line: | |
# python excel_to_csv.py path/to/excel/file.xlsx | |
# Optionally, you can specify a different CSV output path: | |
# python excel_to_csv.py path/to/excel/file.xlsx output.csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got tired of doing this using GUI, so made this.