Spaces:
Sleeping
Sleeping
Create ReadExcelTool.py
Browse files- tools/ReadExcelTool.py +42 -0
tools/ReadExcelTool.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
class ReadExcelTool:
|
| 5 |
+
"""
|
| 6 |
+
Reads an Excel file (.xlsx) and returns the content of the first sheet
|
| 7 |
+
as a formatted markdown table string.
|
| 8 |
+
"""
|
| 9 |
+
name: str = "read_excel_data"
|
| 10 |
+
description: str = "Reads data from an XLSX file and converts the contents of the first sheet into a markdown table string."
|
| 11 |
+
|
| 12 |
+
inputs: Dict[str, Dict[str, Any]] = {
|
| 13 |
+
"file_path": {
|
| 14 |
+
"type": "string",
|
| 15 |
+
"description": "The full path of the .xlsx file to read."
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
output_type: str = "string"
|
| 19 |
+
|
| 20 |
+
def forward(self, file_path: str) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Processes the XLSX file using pandas and returns a string representation.
|
| 23 |
+
"""
|
| 24 |
+
try:
|
| 25 |
+
# Pandas correctly handles the binary format of .xlsx files.
|
| 26 |
+
# We only read the first sheet by default for simplicity.
|
| 27 |
+
df = pd.read_excel(file_path, engine='openpyxl')
|
| 28 |
+
|
| 29 |
+
# Convert the DataFrame to a clean, readable Markdown table string
|
| 30 |
+
content = df.to_markdown(index=False)
|
| 31 |
+
|
| 32 |
+
return content
|
| 33 |
+
except FileNotFoundError:
|
| 34 |
+
return f"Error: File not found at path: {file_path}"
|
| 35 |
+
except Exception as e:
|
| 36 |
+
# Catches potential issues like openpyxl not being available or file corruption
|
| 37 |
+
return f"Error reading Excel file {file_path}. Ensure 'openpyxl' and 'pandas' are installed. Detail: {e}"
|
| 38 |
+
|
| 39 |
+
# Example Usage:
|
| 40 |
+
# tool = ReadExcelTool()
|
| 41 |
+
# excel_content = tool.forward("path/to/your/excel_file.xlsx")
|
| 42 |
+
# print(excel_content)
|