excel_loader.py
2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from __future__ import annotations
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.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())