haileyhalimj@gmail.com
commited on
Commit
Β·
8c95080
1
Parent(s):
e943e9a
add separate function in excel to csv
Browse files
src/preprocess/excel_to_csv_converter.py
CHANGED
|
@@ -2,124 +2,110 @@ import pandas as pd
|
|
| 2 |
import os
|
| 3 |
from pathlib import Path
|
| 4 |
|
| 5 |
-
|
| 6 |
"""
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
Args:
|
| 10 |
-
excel_path (str): Path to the Excel file
|
| 11 |
-
|
| 12 |
-
Returns:
|
| 13 |
-
dict: Dictionary with sheet names and their basic info
|
| 14 |
"""
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
'columns': len(df.columns),
|
| 31 |
-
'column_names': list(df.columns)
|
| 32 |
-
}
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
excel_path (str): Path to the Excel file
|
| 51 |
-
output_dir (str): Output directory for CSV files. If None, uses same directory as Excel file
|
| 52 |
-
"""
|
| 53 |
-
try:
|
| 54 |
-
# Set up output directory
|
| 55 |
if output_dir is None:
|
| 56 |
output_dir = os.path.dirname(excel_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
print(
|
| 65 |
-
print(
|
| 66 |
-
print("
|
| 67 |
|
| 68 |
-
|
|
|
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
df = pd.read_excel(excel_path, sheet_name=sheet_name)
|
| 73 |
-
|
| 74 |
-
# Create a safe filename for the CSV
|
| 75 |
-
safe_filename = "".join(c for c in sheet_name if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 76 |
-
safe_filename = safe_filename.replace(' ', '_')
|
| 77 |
-
csv_filename = f"{safe_filename}.csv"
|
| 78 |
-
csv_path = os.path.join(output_dir, csv_filename)
|
| 79 |
-
|
| 80 |
-
# Save as CSV
|
| 81 |
-
df.to_csv(csv_path, index=False, encoding='utf-8')
|
| 82 |
-
converted_files.append(csv_path)
|
| 83 |
-
|
| 84 |
-
print(f"β
{i}. '{sheet_name}' β {csv_filename}")
|
| 85 |
-
print(f" - Saved {len(df)} rows, {len(df.columns)} columns")
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def main():
|
| 95 |
-
"""Main function to analyze and convert Excel file"""
|
| 96 |
-
|
| 97 |
-
# Define paths
|
| 98 |
-
excel_path = "data/real_data_excel/AI Project document.xlsx"
|
| 99 |
-
output_dir = "data/real_data_excel/converted_csv"
|
| 100 |
-
|
| 101 |
-
# Check if Excel file exists
|
| 102 |
-
if not os.path.exists(excel_path):
|
| 103 |
-
print(f"β Excel file not found: {excel_path}")
|
| 104 |
-
return
|
| 105 |
-
|
| 106 |
-
print("=" * 60)
|
| 107 |
-
print("π EXCEL TO CSV CONVERTER")
|
| 108 |
-
print("=" * 60)
|
| 109 |
-
|
| 110 |
-
# Step 1: Analyze Excel structure
|
| 111 |
-
sheet_info = analyze_excel_structure(excel_path)
|
| 112 |
-
|
| 113 |
-
if sheet_info is None:
|
| 114 |
-
return
|
| 115 |
-
|
| 116 |
-
# Step 2: Convert to CSV
|
| 117 |
-
converted_files = convert_excel_to_csv(excel_path, output_dir)
|
| 118 |
-
|
| 119 |
-
if converted_files:
|
| 120 |
-
print("\nπ Converted files:")
|
| 121 |
-
for file_path in converted_files:
|
| 122 |
-
print(f" - {file_path}")
|
| 123 |
|
| 124 |
if __name__ == "__main__":
|
| 125 |
main()
|
|
|
|
| 2 |
import os
|
| 3 |
from pathlib import Path
|
| 4 |
|
| 5 |
+
class ExcelToCsvConverter:
|
| 6 |
"""
|
| 7 |
+
Convert an Excel file to CSV files.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
+
|
| 10 |
+
def __init__(self, excel_path, output_dir=None):
|
| 11 |
+
self.excel_path = excel_path
|
| 12 |
+
self.output_dir = output_dir
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def convert_excel_to_csv(excel_path, output_dir=None):
|
| 16 |
+
"""
|
| 17 |
+
Convert each sheet of an Excel file to a separate CSV file.
|
| 18 |
|
| 19 |
+
Args:
|
| 20 |
+
excel_path (str): Path to the Excel file
|
| 21 |
+
output_dir (str): Output directory for CSV files. If None, uses same directory as Excel file
|
| 22 |
+
"""
|
| 23 |
+
try:
|
| 24 |
+
# Set up output directory
|
| 25 |
+
if output_dir is None:
|
| 26 |
+
output_dir = os.path.dirname(excel_path)
|
| 27 |
|
| 28 |
+
# Create output directory if it doesn't exist
|
| 29 |
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# Read Excel file
|
| 32 |
+
excel_file = pd.ExcelFile(excel_path)
|
| 33 |
+
converted_files = []
|
| 34 |
+
|
| 35 |
+
for i, sheet_name in enumerate(excel_file.sheet_names, 1):
|
| 36 |
+
# Read the sheet
|
| 37 |
+
df = pd.read_excel(excel_path, sheet_name=sheet_name)
|
| 38 |
+
|
| 39 |
+
# Create a safe filename for the CSV
|
| 40 |
+
safe_filename = "".join(c for c in sheet_name if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 41 |
+
#for specific sheet name, save the file name and use it later
|
| 42 |
+
self.sheet_name = sheet_name
|
| 43 |
+
self.safe_filename = safe_filename
|
| 44 |
+
safe_filename = safe_filename.replace(' ', '_')
|
| 45 |
+
csv_filename = f"{safe_filename}.csv"
|
| 46 |
+
csv_path = os.path.join(output_dir, csv_filename)
|
| 47 |
+
|
| 48 |
+
# Save as CSV
|
| 49 |
+
df.to_csv(csv_path, index=False, encoding='utf-8')
|
| 50 |
+
converted_files.append(csv_path)
|
| 51 |
+
|
| 52 |
+
print(f"β
{i}. '{sheet_name}' β {csv_filename}")
|
| 53 |
+
print(f" - Saved {len(df)} rows, {len(df.columns)} columns")
|
| 54 |
+
|
| 55 |
+
print(f"\nπ Successfully converted {len(converted_files)} sheets to CSV files!")
|
| 56 |
+
return converted_files
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"β Error converting Excel to CSV: {e}")
|
| 60 |
+
return None
|
| 61 |
|
| 62 |
+
|
| 63 |
+
def convert_specific_sheet_to_csv(excel_path, sheet_name, output_dir=None):
|
| 64 |
+
"""
|
| 65 |
+
Convert a specific sheet of an Excel file to a CSV file.
|
| 66 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
if output_dir is None:
|
| 68 |
output_dir = os.path.dirname(excel_path)
|
| 69 |
+
|
| 70 |
+
df = pd.read_excel(excel_path, sheet_name=sheet_name)
|
| 71 |
+
safe_filename = "".join(c for c in sheet_name if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 72 |
+
safe_filename = safe_filename.replace(' ', '_')
|
| 73 |
+
csv_filename = f"{safe_filename}.csv"
|
| 74 |
+
csv_path = os.path.join(output_dir, csv_filename)
|
| 75 |
+
df.to_csv(csv_path, index=False, encoding='utf-8')
|
| 76 |
+
print(f"β
{sheet_name} β {csv_filename}")
|
| 77 |
+
|
| 78 |
+
return csv_path
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
"""Main function to analyze and convert Excel file"""
|
| 82 |
|
| 83 |
+
# Define paths
|
| 84 |
+
excel_path = "data/real_data_excel/AI Project document.xlsx"
|
| 85 |
+
output_dir = "data/real_data_excel/converted_csv"
|
| 86 |
|
| 87 |
+
# Check if Excel file exists
|
| 88 |
+
if not os.path.exists(excel_path):
|
| 89 |
+
print(f"β Excel file not found: {excel_path}")
|
| 90 |
+
return
|
| 91 |
|
| 92 |
+
print("=" * 60)
|
| 93 |
+
print("π EXCEL TO CSV CONVERTER")
|
| 94 |
+
print("=" * 60)
|
| 95 |
|
| 96 |
+
# Step 1: Analyze Excel structure
|
| 97 |
+
sheet_info = analyze_excel_structure(excel_path)
|
| 98 |
|
| 99 |
+
if sheet_info is None:
|
| 100 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# Step 2: Convert to CSV
|
| 103 |
+
converted_files = convert_excel_to_csv(excel_path, output_dir)
|
| 104 |
|
| 105 |
+
if converted_files:
|
| 106 |
+
print("\nπ Converted files:")
|
| 107 |
+
for file_path in converted_files:
|
| 108 |
+
print(f" - {file_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
if __name__ == "__main__":
|
| 111 |
main()
|