JatinAutonomousLabs's picture
Upload 2 files
7477da2 verified
#!/usr/bin/env python3
"""Excel File Handler Plugin"""
import pandas as pd
from typing import Dict, Any
from pathlib import Path
class ExcelHandler:
"""Handle Excel files with multi-sheet support."""
def __init__(self):
self.supported_extensions = ['.xlsx', '.xls', '.xlsm']
def can_handle(self, filename: str) -> bool:
return Path(filename).suffix.lower() in self.supported_extensions
def load(self, file_path: str) -> Dict[str, Any]:
try:
excel_file = pd.ExcelFile(file_path)
sheets = {}
for sheet_name in excel_file.sheet_names:
sheets[sheet_name] = pd.read_excel(file_path, sheet_name=sheet_name)
combined_df = pd.concat(sheets.values(), ignore_index=True)
metadata = {"sheet_count": len(sheets), "total_rows": len(combined_df)}
return {"success": True, "sheets": sheets, "combined": combined_df, "metadata": metadata, "file_type": "excel"}
except Exception as e:
return {"success": False, "error": f"Failed to load Excel: {str(e)}", "file_type": "excel"}
def preview(self, data: Dict[str, Any], max_rows: int = 5) -> str:
if not data.get("success"):
return f"<p class='text-red-500'>Error: {data.get('error')}</p>"
html = f"<h4>📊 Excel File</h4><p><strong>Sheets:</strong> {data['metadata']['sheet_count']}</p>"
html += f"<p><strong>Total Rows:</strong> {data['metadata']['total_rows']:,}</p>"
df = data["combined"]
html += "<h5>Combined Data Preview:</h5>"
html += df.head(max_rows).to_html(index=False, classes="preview-table border w-full text-xs")
return html