File size: 1,667 Bytes
aa3be20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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")