File size: 1,645 Bytes
43e5e58
 
d259fdf
43e5e58
d259fdf
43e5e58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
from typing import Dict, Any
from smolagents.tools import Tool

class ReadExcelTool(Tool):
    """
    Reads an Excel file (.xlsx) and returns the content of the first sheet
    as a formatted markdown table string.
    """
    name: str = "read_excel_data"
    description: str = "Reads data from an XLSX file and converts the contents of the first sheet into a markdown table string."
    
    inputs: Dict[str, Dict[str, Any]] = {
        "file_path": {
            "type": "string",
            "description": "The full path of the .xlsx file to read."
        }
    }
    output_type: str = "string"

    def forward(self, file_path: str) -> str:
        """
        Processes the XLSX file using pandas and returns a string representation.
        """
        try:
            # Pandas correctly handles the binary format of .xlsx files.
            # We only read the first sheet by default for simplicity.
            df = pd.read_excel(file_path, engine='openpyxl')
            
            # Convert the DataFrame to a clean, readable Markdown table string
            content = df.to_markdown(index=False)
            
            return content
        except FileNotFoundError:
            return f"Error: File not found at path: {file_path}"
        except Exception as e:
            # Catches potential issues like openpyxl not being available or file corruption
            return f"Error reading Excel file {file_path}. Ensure 'openpyxl' and 'pandas' are installed. Detail: {e}"

# Example Usage:
# tool = ReadExcelTool()
# excel_content = tool.forward("path/to/your/excel_file.xlsx")
# print(excel_content)