From 9059d33e298939756a869d3ba1849d5364c6e51f Mon Sep 17 00:00:00 2001 From: Nitish Goel Date: Thu, 26 Sep 2024 15:01:59 -0400 Subject: [PATCH] Added script for Excel to CSV --- Excel to CSV/README.md | 10 +++++++++ Excel to CSV/excel_to_csv.py | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 Excel to CSV/README.md create mode 100644 Excel to CSV/excel_to_csv.py diff --git a/Excel to CSV/README.md b/Excel to CSV/README.md new file mode 100644 index 0000000..1d3880e --- /dev/null +++ b/Excel to CSV/README.md @@ -0,0 +1,10 @@ +# Excel to CSV Converter + +## Description +This Python script converts Excel files (.xlsx, .xls) to CSV format. It can be used for batch processing of files and handles multiple Excel sheets. + +## Prerequisites +- Python 3.x +- Libraries: + - pandas + - openpyxl (for .xlsx files) \ No newline at end of file diff --git a/Excel to CSV/excel_to_csv.py b/Excel to CSV/excel_to_csv.py new file mode 100644 index 0000000..b1e5794 --- /dev/null +++ b/Excel to CSV/excel_to_csv.py @@ -0,0 +1,40 @@ +import pandas as pd +import sys +import os + + #excel_file: Path to the Excel file + #output_csv: Path to save the output CSV file + #sheet_name: Name of the sheet to convert. If None, the first sheet is used + +def convert_excel_to_csv(excel_file, output_csv, sheet_name=None): + + + try: + #Checks if the file exists + if not os.path.exists(excel_file): + print(f"Error: The file '{excel_file}' does not exist.") + return + + #Reads the Excel file + if sheet_name: + df = pd.read_excel(excel_file, sheet_name=sheet_name) + else: + df = pd.read_excel(excel_file) + + # Converts the Excel file to CSV foormaat + df.to_csv(output_csv, index=False) + print(f"Successfully converted '{excel_file}' to '{output_csv}'.") + + except ValueError as e: + print(f"Error: {e}") + except Exception as e: + print(f"An error occurred: {e}") + +if __name__ == "__main__": + if len(sys.argv) < 3: + print("Usage: python excel_to_csv.py [sheet_name]") + else: + input_excel_file = sys.argv[1] + output_csv_file = sys.argv[2] + sheet_name = sys.argv[3] if len(sys.argv) > 3 else None + convert_excel_to_csv(input_excel_file, output_csv_file, sheet_name)