Spaces:
Sleeping
Sleeping
| import json | |
| def read_excel(file_path: str, sheet: str = None) -> str: | |
| """Read an Excel file and return its contents as a formatted table. | |
| Args: | |
| file_path: Path to the Excel file (.xlsx) | |
| sheet: Sheet name or index to read (default: first sheet) | |
| Returns: | |
| JSON string with sheet names and formatted table data | |
| """ | |
| try: | |
| import pandas as pd | |
| # Read the Excel file | |
| if sheet is not None: | |
| df = pd.read_excel(file_path, sheet_name=sheet, engine='openpyxl') | |
| else: | |
| df = pd.read_excel(file_path, sheet_name=0, engine='openpyxl') | |
| # Convert to formatted text | |
| table_text = df.to_string(index=False) | |
| result = { | |
| 'sheet': sheet if sheet else 0, | |
| 'columns': list(df.columns), | |
| 'rows': len(df), | |
| 'data': table_text, | |
| } | |
| return json.dumps(result, indent=2) | |
| except Exception as e: | |
| return json.dumps({'error': str(e)}, indent=2) | |