Files
fotoplaner/venv/lib/python3.12/site-packages/pandas/io/excel/_odfreader.py
T
anders 16c54c6653 Tilføjet venv med docling og afhængigheder
Testfiler opdelt i PNG og previews
2026-10-27 12:20:23 +01:00

277 lines
9.5 KiB
Python

from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
cast,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
import pandas as pd
from pandas.io.excel._base import BaseExcelReader
if TYPE_CHECKING:
from odf.opendocument import OpenDocument
from pandas._libs.tslibs.nattype import NaTType
from pandas._typing import (
FilePath,
ReadBuffer,
Scalar,
StorageOptions,
)
class ODFReader(BaseExcelReader["OpenDocument"]):
def __init__(
self,
filepath_or_buffer: FilePath | ReadBuffer[bytes],
storage_options: StorageOptions | None = None,
engine_kwargs: dict[str, Any] | None = None,
) -> None:
"""
Read tables out of OpenDocument formatted files.
Parameters
----------
filepath_or_buffer : str, path to be parsed or
an open readable stream.
storage_options : dict, optional
Extra options that make sense for a particular storage connection,
e.g. host, port, username, password, etc. For HTTP(S) URLs the
key-value pairs are forwarded to ``urllib.request.Request`` as
header options. For other URLs (e.g. starting with "s3://", and
"gcs://") the key-value pairs are forwarded to ``fsspec.open``.
Please see ``fsspec`` and ``urllib`` for more details, and for
more examples on storage options refer `here
<https://pandas.pydata.org/docs/user_guide/io.html?#reading-writing-remote-files>`__.
engine_kwargs : dict, optional
Arbitrary keyword arguments passed to excel engine.
"""
import_optional_dependency("odf")
super().__init__(
filepath_or_buffer,
storage_options=storage_options,
engine_kwargs=engine_kwargs,
)
@property
def _workbook_class(self) -> type[OpenDocument]:
from odf.opendocument import OpenDocument
return OpenDocument
def load_workbook(
self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs
) -> OpenDocument:
from odf.opendocument import load
return load(filepath_or_buffer, **engine_kwargs)
@property
def empty_value(self) -> str:
"""Property for compat with other readers."""
return ""
@property
def sheet_names(self) -> list[str]:
"""Return a list of sheet names present in the document"""
from odf.table import Table
tables = self.book.getElementsByType(Table)
return [t.getAttribute("name") for t in tables]
def get_sheet_by_index(self, index: int):
from odf.table import Table
self.raise_if_bad_sheet_by_index(index)
tables = self.book.getElementsByType(Table)
return tables[index]
def get_sheet_by_name(self, name: str):
from odf.table import Table
self.raise_if_bad_sheet_by_name(name)
tables = self.book.getElementsByType(Table)
for table in tables:
if table.getAttribute("name") == name:
return table
self.close()
raise ValueError(f"sheet {name} not found")
def get_sheet_data(
self, sheet, file_rows_needed: int | None = None
) -> list[list[Scalar | NaTType]]:
"""
Parse an ODF Table into a list of lists
"""
from odf.namespaces import OFFICENS
from odf.table import (
CoveredTableCell,
TableCell,
TableRow,
)
covered_cell_name = CoveredTableCell().qname
table_cell_name = TableCell().qname
cell_names = {covered_cell_name, table_cell_name}
sheet_rows = sheet.getElementsByType(TableRow)
empty_rows = 0
max_row_len = 0
table: list[list[Scalar | NaTType]] = []
for sheet_row in sheet_rows:
empty_cells = 0
table_row: list[Scalar | NaTType] = []
for sheet_cell in sheet_row.childNodes:
if hasattr(sheet_cell, "qname") and sheet_cell.qname in cell_names:
value: Scalar | NaTType
if (
sheet_cell.qname == covered_cell_name
and (OFFICENS, "value") not in sheet_cell.attributes
):
value = self.empty_value
else:
value = self._get_cell_value(sheet_cell)
column_repeat = self._get_column_repeat(sheet_cell)
# Queue up empty values, writing only if content succeeds them
if value == self.empty_value:
empty_cells += column_repeat
else:
table_row.extend([self.empty_value] * empty_cells)
empty_cells = 0
table_row.extend([value] * column_repeat)
if max_row_len < len(table_row):
max_row_len = len(table_row)
row_repeat = self._get_row_repeat(sheet_row)
if len(table_row) == 0:
empty_rows += row_repeat
else:
# add blank rows to our table
table.extend([[self.empty_value]] * empty_rows)
empty_rows = 0
table.extend(table_row for _ in range(row_repeat))
if file_rows_needed is not None and len(table) >= file_rows_needed:
break
# Make our table square
for row in table:
if len(row) < max_row_len:
row.extend([self.empty_value] * (max_row_len - len(row)))
return table
def _get_row_repeat(self, row) -> int:
"""
Return number of times this row was repeated
Repeating an empty row appeared to be a common way
of representing sparse rows in the table.
"""
from odf.namespaces import TABLENS
return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1))
def _get_column_repeat(self, cell) -> int:
from odf.namespaces import TABLENS
return int(cell.attributes.get((TABLENS, "number-columns-repeated"), 1))
def _get_cell_value(self, cell) -> Scalar | NaTType:
from odf.namespaces import OFFICENS
if str(cell) == "#N/A":
return np.nan
cell_type = cell.attributes.get((OFFICENS, "value-type"))
if cell_type == "boolean":
if str(cell) == "TRUE":
return True
return False
if cell_type is None:
return self.empty_value
elif cell_type == "float":
# GH5394
cell_value = float(cell.attributes.get((OFFICENS, "value")))
val = int(cell_value)
if val == cell_value:
return val
return cell_value
elif cell_type == "percentage":
cell_value = cell.attributes.get((OFFICENS, "value"))
return float(cell_value)
elif cell_type == "string":
return self._get_cell_string_value(cell)
elif cell_type == "currency":
cell_value = cell.attributes.get((OFFICENS, "value"))
return float(cell_value)
elif cell_type == "date":
cell_value = cell.attributes.get((OFFICENS, "date-value"))
return pd.Timestamp(cell_value)
elif cell_type == "time":
stamp = pd.Timestamp(str(cell))
# cast needed here because Scalar doesn't include datetime.time
return cast("Scalar", stamp.time())
else:
self.close()
raise ValueError(f"Unrecognized type {cell_type}")
def _get_cell_string_value(self, cell) -> str:
"""
Find and decode OpenDocument text:s tags that represent
a run length encoded sequence of space characters.
"""
from odf.element import Element
from odf.namespaces import (
OFFICENS,
TEXTNS,
)
# NB: built as plain tuples rather than from odf element instances,
# since this runs once per cell.
office_annotation = (OFFICENS, "annotation")
text_s = (TEXTNS, "s")
text_p = (TEXTNS, "p")
text_line_break = (TEXTNS, "line-break")
value = []
seen_paragraph = False
for fragment in cell.childNodes:
if isinstance(fragment, Element):
if fragment.qname == text_s:
spaces = int(fragment.attributes.get((TEXTNS, "c"), 1))
value.append(" " * spaces)
elif fragment.qname == text_line_break:
# GH#55728: an explicit line break within a paragraph.
value.append("\n")
elif fragment.qname == office_annotation:
continue
else:
if fragment.qname == text_p:
# GH#53924: a cell holding several paragraphs shows them
# on separate lines, which is how LibreOffice and Excel
# store a multi-line cell.
if seen_paragraph:
value.append("\n")
seen_paragraph = True
# recursive impl needed in case of nested fragments
# with multiple spaces
# https://github.com/pandas-dev/pandas/pull/36175#discussion_r484639704
value.append(self._get_cell_string_value(fragment))
else:
value.append(str(fragment).strip("\n"))
return "".join(value)