2024-06-01 16:24:10 +08:00
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
|
|
#
|
|
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
#
|
|
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
#
|
|
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
import logging
|
Fix "File contains no valid workbook part" (#9360)
### What problem does this PR solve?
fix "File contains no valid workbook part"
stacktrace:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 54, in _load_excel_to_workbook
return RAGFlowExcelParser._dataframe_to_workbook(df)
File "/ragflow/deepdoc/parser/excel_parser.py", line 69, in _dataframe_to_workbook
ws.cell(row=row_num, column=col_num, value=value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/worksheet/worksheet.py", line 246, in cell
cell.value = value
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 218, in value
self._bind_value(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 197, in _bind_value
value = self.check_string(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 165, in check_string
raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-08-12 14:58:36 +08:00
|
|
|
|
import re
|
2024-01-15 08:46:22 +08:00
|
|
|
|
import sys
|
|
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
|
2025-02-12 12:39:25 +08:00
|
|
|
|
import pandas as pd
|
2025-03-12 19:20:50 +08:00
|
|
|
|
from openpyxl import Workbook, load_workbook
|
|
|
|
|
|
|
|
|
|
|
|
from rag.nlp import find_codec
|
2026-03-23 21:24:40 +08:00
|
|
|
|
from rag.utils.lazy_image import LazyImage
|
2025-02-12 12:39:25 +08:00
|
|
|
|
|
Fix "File contains no valid workbook part" (#9360)
### What problem does this PR solve?
fix "File contains no valid workbook part"
stacktrace:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 54, in _load_excel_to_workbook
return RAGFlowExcelParser._dataframe_to_workbook(df)
File "/ragflow/deepdoc/parser/excel_parser.py", line 69, in _dataframe_to_workbook
ws.cell(row=row_num, column=col_num, value=value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/worksheet/worksheet.py", line 246, in cell
cell.value = value
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 218, in value
self._bind_value(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 197, in _bind_value
value = self.check_string(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 165, in check_string
raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-08-12 14:58:36 +08:00
|
|
|
|
# copied from `/openpyxl/cell/cell.py`
|
2025-09-10 13:02:53 +08:00
|
|
|
|
ILLEGAL_CHARACTERS_RE = re.compile(r"[\000-\010]|[\013-\014]|[\016-\037]")
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
2025-03-12 19:20:50 +08:00
|
|
|
|
|
2025-09-10 13:02:53 +08:00
|
|
|
|
class RAGFlowExcelParser:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _load_excel_to_workbook(file_like_object):
|
2025-03-12 19:20:50 +08:00
|
|
|
|
if isinstance(file_like_object, bytes):
|
|
|
|
|
|
file_like_object = BytesIO(file_like_object)
|
|
|
|
|
|
|
|
|
|
|
|
# Read first 4 bytes to determine file type
|
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
|
file_head = file_like_object.read(4)
|
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
|
|
2025-09-10 13:02:53 +08:00
|
|
|
|
if not (file_head.startswith(b"PK\x03\x04") or file_head.startswith(b"\xd0\xcf\x11\xe0")):
|
2025-07-25 12:04:07 +08:00
|
|
|
|
logging.info("Not an Excel file, converting CSV to Excel Workbook")
|
2025-03-12 19:20:50 +08:00
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
file_like_object.seek(0)
|
2025-12-08 14:28:23 +08:00
|
|
|
|
df = pd.read_csv(file_like_object, on_bad_lines='skip')
|
2025-03-12 19:20:50 +08:00
|
|
|
|
return RAGFlowExcelParser._dataframe_to_workbook(df)
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e_csv:
|
2025-07-25 12:04:07 +08:00
|
|
|
|
raise Exception(f"Failed to parse CSV and convert to Excel Workbook: {e_csv}")
|
2025-03-12 19:20:50 +08:00
|
|
|
|
|
2025-02-12 12:39:25 +08:00
|
|
|
|
try:
|
2025-09-10 13:02:53 +08:00
|
|
|
|
return load_workbook(file_like_object, data_only=True)
|
2025-02-12 12:39:25 +08:00
|
|
|
|
except Exception as e:
|
2025-07-25 12:04:07 +08:00
|
|
|
|
logging.info(f"openpyxl load error: {e}, try pandas instead")
|
2025-03-05 11:55:27 +08:00
|
|
|
|
try:
|
2025-03-12 19:20:50 +08:00
|
|
|
|
file_like_object.seek(0)
|
Add fallback to use 'calamine' parse engine in excel_parser.py (#9374)
### What problem does this PR solve?
add fallback to `calamine` engine when parse error raised using the
default `openpyxl` / `xlrd` engine.
e.g. the following error can be fixed:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 53, in _load_excel_to_workbook
df = pd.read_excel(file_like_object)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 495, in read_excel
io = ExcelFile(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 1567, in __init__
self._reader = self._engines[engine](
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 46, in __init__
super().__init__(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 573, in __init__
self.book = self.load_workbook(self.handles.handle, engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 63, in load_workbook
return open_workbook(file_contents=data, **engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/__init__.py", line 172, in open_workbook
bk = open_workbook_xls(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 68, in open_workbook_xls
bk.biff2_8_load(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 641, in biff2_8_load
cd.locate_named_stream(UNICODE_LITERAL(qname))
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 398, in locate_named_stream
result = self._locate_stream(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 429, in _locate_stream
raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s]))
xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
2025-08-12 12:41:33 +08:00
|
|
|
|
try:
|
2025-10-21 09:52:59 +08:00
|
|
|
|
dfs = pd.read_excel(file_like_object, sheet_name=None)
|
|
|
|
|
|
return RAGFlowExcelParser._dataframe_to_workbook(dfs)
|
Add fallback to use 'calamine' parse engine in excel_parser.py (#9374)
### What problem does this PR solve?
add fallback to `calamine` engine when parse error raised using the
default `openpyxl` / `xlrd` engine.
e.g. the following error can be fixed:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 53, in _load_excel_to_workbook
df = pd.read_excel(file_like_object)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 495, in read_excel
io = ExcelFile(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 1567, in __init__
self._reader = self._engines[engine](
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 46, in __init__
super().__init__(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 573, in __init__
self.book = self.load_workbook(self.handles.handle, engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 63, in load_workbook
return open_workbook(file_contents=data, **engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/__init__.py", line 172, in open_workbook
bk = open_workbook_xls(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 68, in open_workbook_xls
bk.biff2_8_load(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 641, in biff2_8_load
cd.locate_named_stream(UNICODE_LITERAL(qname))
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 398, in locate_named_stream
result = self._locate_stream(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 429, in _locate_stream
raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s]))
xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
2025-08-12 12:41:33 +08:00
|
|
|
|
except Exception as ex:
|
|
|
|
|
|
logging.info(f"pandas with default engine load error: {ex}, try calamine instead")
|
|
|
|
|
|
file_like_object.seek(0)
|
2025-09-10 13:02:53 +08:00
|
|
|
|
df = pd.read_excel(file_like_object, engine="calamine")
|
Add fallback to use 'calamine' parse engine in excel_parser.py (#9374)
### What problem does this PR solve?
add fallback to `calamine` engine when parse error raised using the
default `openpyxl` / `xlrd` engine.
e.g. the following error can be fixed:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 53, in _load_excel_to_workbook
df = pd.read_excel(file_like_object)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 495, in read_excel
io = ExcelFile(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 1567, in __init__
self._reader = self._engines[engine](
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 46, in __init__
super().__init__(
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 573, in __init__
self.book = self.load_workbook(self.handles.handle, engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 63, in load_workbook
return open_workbook(file_contents=data, **engine_kwargs)
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/__init__.py", line 172, in open_workbook
bk = open_workbook_xls(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 68, in open_workbook_xls
bk.biff2_8_load(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 641, in biff2_8_load
cd.locate_named_stream(UNICODE_LITERAL(qname))
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 398, in locate_named_stream
result = self._locate_stream(
File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 429, in _locate_stream
raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s]))
xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
2025-08-12 12:41:33 +08:00
|
|
|
|
return RAGFlowExcelParser._dataframe_to_workbook(df)
|
2025-03-05 11:55:27 +08:00
|
|
|
|
except Exception as e_pandas:
|
2025-07-25 12:04:07 +08:00
|
|
|
|
raise Exception(f"pandas.read_excel error: {e_pandas}, original openpyxl error: {e}")
|
2025-03-12 19:20:50 +08:00
|
|
|
|
|
Fix "File contains no valid workbook part" (#9360)
### What problem does this PR solve?
fix "File contains no valid workbook part"
stacktrace:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 54, in _load_excel_to_workbook
return RAGFlowExcelParser._dataframe_to_workbook(df)
File "/ragflow/deepdoc/parser/excel_parser.py", line 69, in _dataframe_to_workbook
ws.cell(row=row_num, column=col_num, value=value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/worksheet/worksheet.py", line 246, in cell
cell.value = value
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 218, in value
self._bind_value(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 197, in _bind_value
value = self.check_string(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 165, in check_string
raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-08-12 14:58:36 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _clean_dataframe(df: pd.DataFrame):
|
|
|
|
|
|
def clean_string(s):
|
|
|
|
|
|
if isinstance(s, str):
|
|
|
|
|
|
return ILLEGAL_CHARACTERS_RE.sub(" ", s)
|
|
|
|
|
|
return s
|
|
|
|
|
|
|
|
|
|
|
|
return df.apply(lambda col: col.map(clean_string))
|
|
|
|
|
|
|
2026-03-04 18:00:17 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _fill_worksheet_from_dataframe(ws, df: pd.DataFrame):
|
|
|
|
|
|
for col_num, column_name in enumerate(df.columns, 1):
|
|
|
|
|
|
ws.cell(row=1, column=col_num, value=column_name)
|
|
|
|
|
|
for row_num, row in enumerate(df.values, 2):
|
|
|
|
|
|
for col_num, value in enumerate(row, 1):
|
|
|
|
|
|
ws.cell(row=row_num, column=col_num, value=value)
|
|
|
|
|
|
|
2025-03-12 19:20:50 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _dataframe_to_workbook(df):
|
2025-10-21 09:52:59 +08:00
|
|
|
|
if isinstance(df, dict) and len(df) > 1:
|
|
|
|
|
|
return RAGFlowExcelParser._dataframes_to_workbook(df)
|
|
|
|
|
|
|
Fix "File contains no valid workbook part" (#9360)
### What problem does this PR solve?
fix "File contains no valid workbook part"
stacktrace:
```
Traceback (most recent call last):
File "/ragflow/deepdoc/parser/excel_parser.py", line 54, in _load_excel_to_workbook
return RAGFlowExcelParser._dataframe_to_workbook(df)
File "/ragflow/deepdoc/parser/excel_parser.py", line 69, in _dataframe_to_workbook
ws.cell(row=row_num, column=col_num, value=value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/worksheet/worksheet.py", line 246, in cell
cell.value = value
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 218, in value
self._bind_value(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 197, in _bind_value
value = self.check_string(value)
File "/ragflow/.venv/lib/python3.10/site-packages/openpyxl/cell/cell.py", line 165, in check_string
raise IllegalCharacterError(f"{value} cannot be used in worksheets.")
```
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
2025-08-12 14:58:36 +08:00
|
|
|
|
df = RAGFlowExcelParser._clean_dataframe(df)
|
2025-03-12 19:20:50 +08:00
|
|
|
|
wb = Workbook()
|
|
|
|
|
|
ws = wb.active
|
|
|
|
|
|
ws.title = "Data"
|
2026-03-04 18:00:17 +08:00
|
|
|
|
RAGFlowExcelParser._fill_worksheet_from_dataframe(ws, df)
|
2025-03-12 19:20:50 +08:00
|
|
|
|
return wb
|
2026-03-04 18:00:17 +08:00
|
|
|
|
|
2025-10-21 09:52:59 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _dataframes_to_workbook(dfs: dict):
|
|
|
|
|
|
wb = Workbook()
|
|
|
|
|
|
default_sheet = wb.active
|
|
|
|
|
|
wb.remove(default_sheet)
|
2026-03-04 18:00:17 +08:00
|
|
|
|
|
2025-10-21 09:52:59 +08:00
|
|
|
|
for sheet_name, df in dfs.items():
|
|
|
|
|
|
df = RAGFlowExcelParser._clean_dataframe(df)
|
|
|
|
|
|
ws = wb.create_sheet(title=sheet_name)
|
2026-03-04 18:00:17 +08:00
|
|
|
|
RAGFlowExcelParser._fill_worksheet_from_dataframe(ws, df)
|
2025-10-21 09:52:59 +08:00
|
|
|
|
return wb
|
2024-05-20 18:35:15 +08:00
|
|
|
|
|
2025-12-22 10:17:44 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _extract_images_from_worksheet(ws, sheetname=None):
|
|
|
|
|
|
"""
|
|
|
|
|
|
Extract images from a worksheet and enrich them with vision-based descriptions.
|
|
|
|
|
|
|
|
|
|
|
|
Returns: List[dict]
|
|
|
|
|
|
"""
|
|
|
|
|
|
images = getattr(ws, "_images", [])
|
|
|
|
|
|
if not images:
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
raw_items = []
|
|
|
|
|
|
|
|
|
|
|
|
for img in images:
|
|
|
|
|
|
try:
|
|
|
|
|
|
img_bytes = img._data()
|
2026-03-23 21:24:40 +08:00
|
|
|
|
lazy_img = LazyImage([img_bytes])
|
2025-12-22 10:17:44 +08:00
|
|
|
|
|
|
|
|
|
|
anchor = img.anchor
|
|
|
|
|
|
if hasattr(anchor, "_from") and hasattr(anchor, "_to"):
|
|
|
|
|
|
r1, c1 = anchor._from.row + 1, anchor._from.col + 1
|
|
|
|
|
|
r2, c2 = anchor._to.row + 1, anchor._to.col + 1
|
|
|
|
|
|
if r1 == r2 and c1 == c2:
|
|
|
|
|
|
span = "single_cell"
|
|
|
|
|
|
else:
|
|
|
|
|
|
span = "multi_cell"
|
|
|
|
|
|
else:
|
|
|
|
|
|
r1, c1 = anchor._from.row + 1, anchor._from.col + 1
|
|
|
|
|
|
r2, c2 = r1, c1
|
|
|
|
|
|
span = "single_cell"
|
|
|
|
|
|
|
|
|
|
|
|
item = {
|
|
|
|
|
|
"sheet": sheetname or ws.title,
|
2026-03-23 21:24:40 +08:00
|
|
|
|
"image": lazy_img,
|
2025-12-22 10:17:44 +08:00
|
|
|
|
"image_description": "",
|
|
|
|
|
|
"row_from": r1,
|
|
|
|
|
|
"col_from": c1,
|
|
|
|
|
|
"row_to": r2,
|
|
|
|
|
|
"col_to": c2,
|
|
|
|
|
|
"span_type": span,
|
|
|
|
|
|
}
|
|
|
|
|
|
raw_items.append(item)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
continue
|
|
|
|
|
|
return raw_items
|
|
|
|
|
|
|
2026-02-06 14:43:52 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _get_actual_row_count(ws):
|
|
|
|
|
|
max_row = ws.max_row
|
|
|
|
|
|
if not max_row:
|
|
|
|
|
|
return 0
|
|
|
|
|
|
if max_row <= 10000:
|
|
|
|
|
|
return max_row
|
|
|
|
|
|
|
|
|
|
|
|
max_col = min(ws.max_column or 1, 50)
|
|
|
|
|
|
|
|
|
|
|
|
def row_has_data(row_idx):
|
|
|
|
|
|
for col_idx in range(1, max_col + 1):
|
|
|
|
|
|
cell = ws.cell(row=row_idx, column=col_idx)
|
|
|
|
|
|
if cell.value is not None and str(cell.value).strip():
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
if not any(row_has_data(i) for i in range(1, min(101, max_row + 1))):
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
left, right = 1, max_row
|
|
|
|
|
|
last_data_row = 1
|
|
|
|
|
|
|
|
|
|
|
|
while left <= right:
|
|
|
|
|
|
mid = (left + right) // 2
|
|
|
|
|
|
found = False
|
|
|
|
|
|
for r in range(mid, min(mid + 10, max_row + 1)):
|
|
|
|
|
|
if row_has_data(r):
|
|
|
|
|
|
found = True
|
|
|
|
|
|
last_data_row = max(last_data_row, r)
|
|
|
|
|
|
break
|
|
|
|
|
|
if found:
|
|
|
|
|
|
left = mid + 1
|
|
|
|
|
|
else:
|
|
|
|
|
|
right = mid - 1
|
|
|
|
|
|
|
|
|
|
|
|
for r in range(last_data_row, min(last_data_row + 500, max_row + 1)):
|
|
|
|
|
|
if row_has_data(r):
|
|
|
|
|
|
last_data_row = r
|
|
|
|
|
|
|
|
|
|
|
|
return last_data_row
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _get_rows_limited(ws):
|
|
|
|
|
|
actual_rows = RAGFlowExcelParser._get_actual_row_count(ws)
|
|
|
|
|
|
if actual_rows == 0:
|
|
|
|
|
|
return []
|
|
|
|
|
|
return list(ws.iter_rows(min_row=1, max_row=actual_rows))
|
|
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
def html(self, fnm, chunk_rows=256):
|
2025-08-15 17:00:34 +08:00
|
|
|
|
from html import escape
|
|
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
|
|
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb_chunks = []
|
2025-08-15 17:00:34 +08:00
|
|
|
|
|
|
|
|
|
|
def _fmt(v):
|
|
|
|
|
|
if v is None:
|
|
|
|
|
|
return ""
|
|
|
|
|
|
return str(v).strip()
|
|
|
|
|
|
|
2024-03-20 16:56:16 +08:00
|
|
|
|
for sheetname in wb.sheetnames:
|
|
|
|
|
|
ws = wb[sheetname]
|
2025-10-28 09:40:37 +08:00
|
|
|
|
try:
|
2026-02-06 14:43:52 +08:00
|
|
|
|
rows = RAGFlowExcelParser._get_rows_limited(ws)
|
2025-10-28 09:40:37 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logging.warning(f"Skip sheet '{sheetname}' due to rows access error: {e}")
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
|
continue
|
2024-05-20 18:35:15 +08:00
|
|
|
|
|
|
|
|
|
|
tb_rows_0 = "<tr>"
|
2024-03-27 11:33:46 +08:00
|
|
|
|
for t in list(rows[0]):
|
2025-08-15 17:00:34 +08:00
|
|
|
|
tb_rows_0 += f"<th>{escape(_fmt(t.value))}</th>"
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb_rows_0 += "</tr>"
|
|
|
|
|
|
|
2026-06-08 05:16:45 -04:00
|
|
|
|
# rows[0] is the header; split the remaining data rows into
|
|
|
|
|
|
# ceil(n_data / chunk_rows) chunks. Using +1 here over-counts by one
|
|
|
|
|
|
# when the data-row count is an exact multiple of chunk_rows and emits
|
|
|
|
|
|
# a spurious header-only chunk.
|
|
|
|
|
|
n_data_rows = len(rows) - 1
|
|
|
|
|
|
for chunk_i in range((n_data_rows + chunk_rows - 1) // chunk_rows):
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb = ""
|
|
|
|
|
|
tb += f"<table><caption>{sheetname}</caption>"
|
|
|
|
|
|
tb += tb_rows_0
|
2025-09-10 13:02:53 +08:00
|
|
|
|
for r in list(rows[1 + chunk_i * chunk_rows : min(1 + (chunk_i + 1) * chunk_rows, len(rows))]):
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb += "<tr>"
|
|
|
|
|
|
for i, c in enumerate(r):
|
|
|
|
|
|
if c.value is None:
|
|
|
|
|
|
tb += "<td></td>"
|
|
|
|
|
|
else:
|
2025-09-05 09:58:03 +08:00
|
|
|
|
tb += f"<td>{escape(_fmt(c.value))}</td>"
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb += "</tr>"
|
|
|
|
|
|
tb += "</table>\n"
|
|
|
|
|
|
tb_chunks.append(tb)
|
|
|
|
|
|
|
|
|
|
|
|
return tb_chunks
|
2024-03-20 16:56:16 +08:00
|
|
|
|
|
2025-08-28 18:40:32 +08:00
|
|
|
|
def markdown(self, fnm):
|
|
|
|
|
|
import pandas as pd
|
2025-09-10 13:02:53 +08:00
|
|
|
|
|
2025-08-28 18:40:32 +08:00
|
|
|
|
file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
|
2025-09-10 13:02:53 +08:00
|
|
|
|
try:
|
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
|
df = pd.read_excel(file_like_object)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logging.warning(f"Parse spreadsheet error: {e}, trying to interpret as CSV file")
|
|
|
|
|
|
file_like_object.seek(0)
|
2025-12-08 14:28:23 +08:00
|
|
|
|
df = pd.read_csv(file_like_object, on_bad_lines='skip')
|
2025-09-10 13:02:53 +08:00
|
|
|
|
df = df.replace(r"^\s*$", "", regex=True)
|
2025-08-28 18:40:32 +08:00
|
|
|
|
return df.to_markdown(index=False)
|
|
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
def __call__(self, fnm):
|
2025-03-05 11:55:27 +08:00
|
|
|
|
file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
|
|
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
|
2025-02-12 12:39:25 +08:00
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
res = []
|
|
|
|
|
|
for sheetname in wb.sheetnames:
|
|
|
|
|
|
ws = wb[sheetname]
|
2025-10-28 09:40:37 +08:00
|
|
|
|
try:
|
2026-02-06 14:43:52 +08:00
|
|
|
|
rows = RAGFlowExcelParser._get_rows_limited(ws)
|
2025-10-28 09:40:37 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logging.warning(f"Skip sheet '{sheetname}' due to rows access error: {e}")
|
|
|
|
|
|
continue
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
|
continue
|
2024-01-15 08:46:22 +08:00
|
|
|
|
ti = list(rows[0])
|
|
|
|
|
|
for r in list(rows[1:]):
|
2024-12-08 14:21:12 +08:00
|
|
|
|
fields = []
|
2024-03-27 11:33:46 +08:00
|
|
|
|
for i, c in enumerate(r):
|
2026-06-25 21:30:09 -04:00
|
|
|
|
if c.value is None or str(c.value).strip() == "":
|
2024-03-27 11:33:46 +08:00
|
|
|
|
continue
|
2024-01-15 08:46:22 +08:00
|
|
|
|
t = str(ti[i].value) if i < len(ti) else ""
|
2024-03-12 11:57:08 +08:00
|
|
|
|
t += (":" if t else "") + str(c.value)
|
2024-12-08 14:21:12 +08:00
|
|
|
|
fields.append(t)
|
2026-02-06 14:43:52 +08:00
|
|
|
|
if not fields:
|
|
|
|
|
|
continue
|
2024-12-08 14:21:12 +08:00
|
|
|
|
line = "; ".join(fields)
|
2024-03-27 11:33:46 +08:00
|
|
|
|
if sheetname.lower().find("sheet") < 0:
|
2024-12-08 14:21:12 +08:00
|
|
|
|
line += " ——" + sheetname
|
|
|
|
|
|
res.append(line)
|
2024-01-15 08:46:22 +08:00
|
|
|
|
return res
|
|
|
|
|
|
|
2024-03-12 11:57:08 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def row_number(fnm, binary):
|
|
|
|
|
|
if fnm.split(".")[-1].lower().find("xls") >= 0:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(BytesIO(binary))
|
2024-03-12 11:57:08 +08:00
|
|
|
|
total = 0
|
2026-02-06 14:43:52 +08:00
|
|
|
|
|
2024-03-12 11:57:08 +08:00
|
|
|
|
for sheetname in wb.sheetnames:
|
2026-02-06 14:43:52 +08:00
|
|
|
|
try:
|
|
|
|
|
|
ws = wb[sheetname]
|
|
|
|
|
|
total += RAGFlowExcelParser._get_actual_row_count(ws)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logging.warning(f"Skip sheet '{sheetname}' due to rows access error: {e}")
|
|
|
|
|
|
continue
|
2024-12-19 17:30:26 +08:00
|
|
|
|
return total
|
2024-03-12 11:57:08 +08:00
|
|
|
|
|
|
|
|
|
|
if fnm.split(".")[-1].lower() in ["csv", "txt"]:
|
2024-04-19 18:02:53 +08:00
|
|
|
|
encoding = find_codec(binary)
|
2024-05-07 12:25:47 +08:00
|
|
|
|
txt = binary.decode(encoding, errors="ignore")
|
2024-03-12 11:57:08 +08:00
|
|
|
|
return len(txt.split("\n"))
|
|
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2024-04-28 13:19:54 +08:00
|
|
|
|
psr = RAGFlowExcelParser()
|
2024-01-15 08:46:22 +08:00
|
|
|
|
psr(sys.argv[1])
|