mirror of
https://github.com/HKUDS/nanobot.git
synced 2026-08-04 08:28:36 +00:00
fix: use context manager in _extract_xlsx to prevent resource leak
This commit is contained in:
parent
e15705b471
commit
a00beebd06
@ -133,19 +133,18 @@ def _extract_docx(path: Path) -> str:
|
|||||||
def _extract_xlsx(path: Path) -> str:
|
def _extract_xlsx(path: Path) -> str:
|
||||||
"""Extract text from XLSX using openpyxl."""
|
"""Extract text from XLSX using openpyxl."""
|
||||||
try:
|
try:
|
||||||
wb = load_workbook(path, read_only=True, data_only=True)
|
with load_workbook(path, read_only=True, data_only=True) as wb:
|
||||||
sheets: list[str] = []
|
sheets: list[str] = []
|
||||||
for sheet_name in wb.sheetnames:
|
for sheet_name in wb.sheetnames:
|
||||||
ws = wb[sheet_name]
|
ws = wb[sheet_name]
|
||||||
rows: list[str] = []
|
rows: list[str] = []
|
||||||
for row in ws.iter_rows(values_only=True):
|
for row in ws.iter_rows(values_only=True):
|
||||||
row_text = "\t".join(str(cell) if cell is not None else "" for cell in row)
|
row_text = "\t".join(str(cell) if cell is not None else "" for cell in row)
|
||||||
if row_text.strip():
|
if row_text.strip():
|
||||||
rows.append(row_text)
|
rows.append(row_text)
|
||||||
if rows:
|
if rows:
|
||||||
sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows))
|
sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows))
|
||||||
wb.close()
|
return _truncate("\n\n".join(sheets), _MAX_TEXT_LENGTH)
|
||||||
return _truncate("\n\n".join(sheets), _MAX_TEXT_LENGTH)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("Failed to extract XLSX {}: {}", path, e)
|
logger.error("Failed to extract XLSX {}: {}", path, e)
|
||||||
return f"[error: failed to extract XLSX: {e!s}]"
|
return f"[error: failed to extract XLSX: {e!s}]"
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user