excel.py 2.27 KB
from __future__ import annotations

from src.rag.ingestion.loaders.base import DocumentBlock, register_loader
from src.rag.ingestion.loaders.common import enrich_blocks
from src.rag.core.utils import file_ext


class ExcelLoader:
    extensions = {".xlsx", ".xls", ".xlx"}

    def load(self, path: str) -> list[DocumentBlock]:
        import pandas as pd

        try:
            sheets = pd.read_excel(path, sheet_name=None)
        except Exception as exc:
            if file_ext(path) == ".xlx":
                raise RuntimeError(".xlx 解析失败,请确认文件是否应为 .xls 或 .xlsx。") from exc
            raise

        blocks: list[DocumentBlock] = []
        for sheet_name, df in sheets.items():
            df = df.dropna(how="all")
            if df.empty:
                continue
            headers = [str(c) for c in df.columns]
            batch_size = 35
            for start in range(0, len(df), batch_size):
                sub = df.iloc[start : start + batch_size]
                rows = ["| " + " | ".join(headers) + " |", "| " + " | ".join(["---"] * len(headers)) + " |"]
                rows.extend("| " + " | ".join("" if v != v else str(v) for v in row) + " |" for row in sub.values.tolist())
                blocks.append(
                    DocumentBlock(
                        text="\n".join(rows),
                        block_type="table",
                        title_path=str(sheet_name),
                        sheet_name=str(sheet_name),
                        row_start=start + 1,
                        row_end=start + len(sub),
                        source_offset=start,
                        metadata={
                            "parse_method": "excel_table",
                            "content_role": "table",
                            "content_kind": "table",
                            "section_path": [str(sheet_name)],
                            "section_title": str(sheet_name),
                            "table_header": headers,
                            "table_id": f"{sheet_name}:{start + 1}-{start + len(sub)}",
                            "table_row_count": len(sub),
                        },
                    )
                )
        return enrich_blocks(blocks, parse_method="excel_table")


register_loader(ExcelLoader())