From a00beebd0635243fa34c2cab673562541604ceba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E6=98=9F=E6=9D=B0?= <1198425718@qq.com> Date: Tue, 21 Apr 2026 14:44:37 +0800 Subject: [PATCH] fix: use context manager in _extract_xlsx to prevent resource leak --- nanobot/utils/document.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/nanobot/utils/document.py b/nanobot/utils/document.py index 89ffcca9..b73d91b4 100644 --- a/nanobot/utils/document.py +++ b/nanobot/utils/document.py @@ -133,19 +133,18 @@ def _extract_docx(path: Path) -> str: def _extract_xlsx(path: Path) -> str: """Extract text from XLSX using openpyxl.""" try: - wb = load_workbook(path, read_only=True, data_only=True) - sheets: list[str] = [] - for sheet_name in wb.sheetnames: - ws = wb[sheet_name] - rows: list[str] = [] - 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) - if row_text.strip(): - rows.append(row_text) - if rows: - sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows)) - wb.close() - return _truncate("\n\n".join(sheets), _MAX_TEXT_LENGTH) + with load_workbook(path, read_only=True, data_only=True) as wb: + sheets: list[str] = [] + for sheet_name in wb.sheetnames: + ws = wb[sheet_name] + rows: list[str] = [] + 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) + if row_text.strip(): + rows.append(row_text) + if rows: + sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows)) + return _truncate("\n\n".join(sheets), _MAX_TEXT_LENGTH) except Exception as e: logger.error("Failed to extract XLSX {}: {}", path, e) return f"[error: failed to extract XLSX: {e!s}]"