Files

50 lines
1.9 KiB
Python

import io
import pandas as pd
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.base import SourceTable
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.tabular import FileConnector
@register_connector
class ExcelConnector(FileConnector):
"""`dtype=object` keeps each cell as the value openpyxl read; column
typing would turn an integer column with a blank cell into floats."""
kind = "excel"
label = "Libro de Excel"
description = "Cada hoja del libro se ofrece como tabla"
category = "file"
icon = "grid_on"
extensions = ("xlsx", "xlsm")
option_names = ("sheet_name",)
def __init__(self, raw: bytes, *, sheet_name: str | int | None = None):
try:
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
except Exception as exc:
raise ConnectorError(f"no se pudo abrir el archivo de Excel: {exc}") from exc
self._sheet = sheet_name if sheet_name not in (None, "") else self._workbook.sheet_names[0]
if isinstance(self._sheet, str) and self._sheet not in self._workbook.sheet_names:
raise ConnectorError(f"no existe la hoja {self._sheet!r} (disponibles: {self._workbook.sheet_names})")
try:
self._df = self._workbook.parse(self._sheet, dtype=object)
except Exception as exc:
raise ConnectorError(f"no se pudo leer la hoja {self._sheet!r}: {exc}") from exc
self._df.columns = [str(c).strip() for c in self._df.columns]
def list_sheets(self) -> list[str]:
return list(self._workbook.sheet_names)
def tables(self) -> list[SourceTable]:
return [SourceTable(name, {"sheet_name": name}, kind="sheet") for name in self.list_sheets()]
def _dataframe(self) -> pd.DataFrame:
return self._df
def metadata(self) -> dict:
return {"sheets": self.list_sheets(), "sheet_name": self._sheet}