Spaces:
Running
Running
import os | |
import requests | |
from openpyxl import load_workbook | |
# Excel Tool | |
def excel_to_csv(excel_path: str) -> str: | |
""" | |
Given an Excel file path or URL and an optional sheet name, | |
reads the spreadsheet using openpyxl and returns its contents as CSV text. | |
Args: | |
excel_path (str): The URL or local file path of the Excel file to convert. | |
Returns: | |
str: The CSV-formatted content of the sheet. | |
""" | |
print("--- Converting Excel to CSV ---") | |
print(f"Excel Path: {excel_path}") | |
excel_path = os.path.join("./GAIA_resource/", excel_path) | |
try: | |
# Load workbook from URL or local file | |
if excel_path.startswith("http"): | |
response = requests.get(excel_path) | |
response.raise_for_status() | |
data_stream = BytesIO(response.content) | |
wb = load_workbook(filename=data_stream, data_only=True) | |
else: | |
wb = load_workbook(filename=excel_path, data_only=True) | |
# Select worksheet | |
ws = wb.active | |
# Build CSV lines manually | |
lines = [] | |
for row in ws.iter_rows(values_only=True): | |
# Convert each cell to string, using empty string for None | |
str_cells = ["" if cell is None else str(cell) for cell in row] | |
# Join cells with commas | |
line = ",".join(str_cells) | |
lines.append(line) | |
# Combine all lines into one CSV string | |
print("Converted Excel to CSV result : ", lines) | |
return "\n".join(lines) | |
except Exception as e: | |
return f"Error converting Excel to CSV: {e}" | |
excel_to_csv("7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx") |