|
| 1 | +from typing import List |
| 2 | + |
| 3 | +from pandas.compat._optional import import_optional_dependency |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +from pandas._typing import FilePathOrBuffer, Scalar |
| 7 | + |
| 8 | +from pandas.io.excel._base import _BaseExcelReader |
| 9 | + |
| 10 | + |
| 11 | +class _ODFReader(_BaseExcelReader): |
| 12 | + """Read tables out of OpenDocument formatted files |
| 13 | +
|
| 14 | + Parameters |
| 15 | + ---------- |
| 16 | + filepath_or_buffer: string, path to be parsed or |
| 17 | + an open readable stream. |
| 18 | + """ |
| 19 | + def __init__(self, filepath_or_buffer: FilePathOrBuffer): |
| 20 | + import_optional_dependency("odf") |
| 21 | + super().__init__(filepath_or_buffer) |
| 22 | + |
| 23 | + @property |
| 24 | + def _workbook_class(self): |
| 25 | + from odf.opendocument import OpenDocument |
| 26 | + return OpenDocument |
| 27 | + |
| 28 | + def load_workbook(self, filepath_or_buffer: FilePathOrBuffer): |
| 29 | + from odf.opendocument import load |
| 30 | + return load(filepath_or_buffer) |
| 31 | + |
| 32 | + @property |
| 33 | + def empty_value(self) -> str: |
| 34 | + """Property for compat with other readers.""" |
| 35 | + return '' |
| 36 | + |
| 37 | + @property |
| 38 | + def sheet_names(self) -> List[str]: |
| 39 | + """Return a list of sheet names present in the document""" |
| 40 | + from odf.table import Table |
| 41 | + |
| 42 | + tables = self.book.getElementsByType(Table) |
| 43 | + return [t.getAttribute("name") for t in tables] |
| 44 | + |
| 45 | + def get_sheet_by_index(self, index: int): |
| 46 | + from odf.table import Table |
| 47 | + tables = self.book.getElementsByType(Table) |
| 48 | + return tables[index] |
| 49 | + |
| 50 | + def get_sheet_by_name(self, name: str): |
| 51 | + from odf.table import Table |
| 52 | + |
| 53 | + tables = self.book.getElementsByType(Table) |
| 54 | + |
| 55 | + for table in tables: |
| 56 | + if table.getAttribute("name") == name: |
| 57 | + return table |
| 58 | + |
| 59 | + raise ValueError("sheet {name} not found".format(name)) |
| 60 | + |
| 61 | + def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: |
| 62 | + """Parse an ODF Table into a list of lists |
| 63 | + """ |
| 64 | + from odf.table import CoveredTableCell, TableCell, TableRow |
| 65 | + |
| 66 | + covered_cell_name = CoveredTableCell().qname |
| 67 | + table_cell_name = TableCell().qname |
| 68 | + cell_names = {covered_cell_name, table_cell_name} |
| 69 | + |
| 70 | + sheet_rows = sheet.getElementsByType(TableRow) |
| 71 | + empty_rows = 0 |
| 72 | + max_row_len = 0 |
| 73 | + |
| 74 | + table = [] # type: List[List[Scalar]] |
| 75 | + |
| 76 | + for i, sheet_row in enumerate(sheet_rows): |
| 77 | + sheet_cells = [x for x in sheet_row.childNodes |
| 78 | + if x.qname in cell_names] |
| 79 | + empty_cells = 0 |
| 80 | + table_row = [] # type: List[Scalar] |
| 81 | + |
| 82 | + for j, sheet_cell in enumerate(sheet_cells): |
| 83 | + if sheet_cell.qname == table_cell_name: |
| 84 | + value = self._get_cell_value(sheet_cell, convert_float) |
| 85 | + else: |
| 86 | + value = self.empty_value |
| 87 | + |
| 88 | + column_repeat = self._get_column_repeat(sheet_cell) |
| 89 | + |
| 90 | + # Queue up empty values, writing only if content succeeds them |
| 91 | + if value == self.empty_value: |
| 92 | + empty_cells += column_repeat |
| 93 | + else: |
| 94 | + table_row.extend([self.empty_value] * empty_cells) |
| 95 | + empty_cells = 0 |
| 96 | + table_row.extend([value] * column_repeat) |
| 97 | + |
| 98 | + if max_row_len < len(table_row): |
| 99 | + max_row_len = len(table_row) |
| 100 | + |
| 101 | + row_repeat = self._get_row_repeat(sheet_row) |
| 102 | + if self._is_empty_row(sheet_row): |
| 103 | + empty_rows += row_repeat |
| 104 | + else: |
| 105 | + # add blank rows to our table |
| 106 | + table.extend([[self.empty_value]] * empty_rows) |
| 107 | + empty_rows = 0 |
| 108 | + for _ in range(row_repeat): |
| 109 | + table.append(table_row) |
| 110 | + |
| 111 | + # Make our table square |
| 112 | + for row in table: |
| 113 | + if len(row) < max_row_len: |
| 114 | + row.extend([self.empty_value] * (max_row_len - len(row))) |
| 115 | + |
| 116 | + return table |
| 117 | + |
| 118 | + def _get_row_repeat(self, row) -> int: |
| 119 | + """Return number of times this row was repeated |
| 120 | + Repeating an empty row appeared to be a common way |
| 121 | + of representing sparse rows in the table. |
| 122 | + """ |
| 123 | + from odf.namespaces import TABLENS |
| 124 | + |
| 125 | + return int(row.attributes.get((TABLENS, 'number-rows-repeated'), 1)) |
| 126 | + |
| 127 | + def _get_column_repeat(self, cell) -> int: |
| 128 | + from odf.namespaces import TABLENS |
| 129 | + return int(cell.attributes.get( |
| 130 | + (TABLENS, 'number-columns-repeated'), 1)) |
| 131 | + |
| 132 | + def _is_empty_row(self, row) -> bool: |
| 133 | + """Helper function to find empty rows |
| 134 | + """ |
| 135 | + for column in row.childNodes: |
| 136 | + if len(column.childNodes) > 0: |
| 137 | + return False |
| 138 | + |
| 139 | + return True |
| 140 | + |
| 141 | + def _get_cell_value(self, cell, convert_float: bool) -> Scalar: |
| 142 | + from odf.namespaces import OFFICENS |
| 143 | + cell_type = cell.attributes.get((OFFICENS, 'value-type')) |
| 144 | + if cell_type == 'boolean': |
| 145 | + if str(cell) == "TRUE": |
| 146 | + return True |
| 147 | + return False |
| 148 | + if cell_type is None: |
| 149 | + return self.empty_value |
| 150 | + elif cell_type == 'float': |
| 151 | + # GH5394 |
| 152 | + cell_value = float(cell.attributes.get((OFFICENS, 'value'))) |
| 153 | + |
| 154 | + if cell_value == 0. and str(cell) != cell_value: # NA handling |
| 155 | + return str(cell) |
| 156 | + |
| 157 | + if convert_float: |
| 158 | + val = int(cell_value) |
| 159 | + if val == cell_value: |
| 160 | + return val |
| 161 | + return cell_value |
| 162 | + elif cell_type == 'percentage': |
| 163 | + cell_value = cell.attributes.get((OFFICENS, 'value')) |
| 164 | + return float(cell_value) |
| 165 | + elif cell_type == 'string': |
| 166 | + return str(cell) |
| 167 | + elif cell_type == 'currency': |
| 168 | + cell_value = cell.attributes.get((OFFICENS, 'value')) |
| 169 | + return float(cell_value) |
| 170 | + elif cell_type == 'date': |
| 171 | + cell_value = cell.attributes.get((OFFICENS, 'date-value')) |
| 172 | + return pd.to_datetime(cell_value) |
| 173 | + elif cell_type == 'time': |
| 174 | + return pd.to_datetime(str(cell)).time() |
| 175 | + else: |
| 176 | + raise ValueError('Unrecognized type {}'.format(cell_type)) |
0 commit comments