fastexcel
1from __future__ import annotations 2 3import typing 4from collections.abc import Callable 5from typing import TYPE_CHECKING, Literal, TypeAlias 6 7if TYPE_CHECKING: 8 import pandas as pd 9 import polars as pl 10 import pyarrow as pa 11 12from os.path import expanduser 13from pathlib import Path 14 15try: 16 import importlib.util 17 18 importlib.util.find_spec("pyarrow") 19 _PYARROW_AVAILABLE = True 20except ImportError: 21 _PYARROW_AVAILABLE = False 22 23from ._fastexcel import ( 24 DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 25 DEFAULT_UNNAMED_COLUMN_PREFIX, 26 ArrowError, 27 CalamineCellError, 28 CalamineError, 29 CannotRetrieveCellDataError, 30 CellError, 31 CellErrors, 32 ColumnInfo, 33 ColumnInfoNoDtype, 34 ColumnNotFoundError, 35 DefinedName, 36 FastExcelError, 37 InvalidParametersError, 38 SheetNotFoundError, 39 UnsupportedColumnTypeCombinationError, 40 WorkbookProperties, 41 __version__, 42 _ExcelReader, 43 _ExcelSheet, 44 _ExcelTable, 45) 46from ._fastexcel import read_excel as _read_excel 47 48DType = Literal["null", "int", "float", "string", "boolean", "datetime", "date", "duration"] 49DTypeMap: TypeAlias = "dict[str | int, DType]" 50ColumnNameFrom: TypeAlias = Literal["provided", "looked_up", "generated"] 51DTypeFrom: TypeAlias = Literal[ 52 "provided_for_all", "provided_by_index", "provided_by_name", "guessed" 53] 54SheetVisible: TypeAlias = Literal["visible", "hidden", "veryhidden"] 55 56 57class ExcelSheet: 58 """A class representing a single sheet in an Excel File""" 59 60 def __init__(self, sheet: _ExcelSheet) -> None: 61 self._sheet = sheet 62 63 @property 64 def name(self) -> str: 65 """The name of the sheet""" 66 return self._sheet.name 67 68 @property 69 def width(self) -> int: 70 """The sheet's width""" 71 return self._sheet.width 72 73 @property 74 def height(self) -> int: 75 """The sheet's height, with `skip_rows` and `nrows` applied""" 76 return self._sheet.height 77 78 @property 79 def total_height(self) -> int: 80 """The sheet's total height""" 81 return self._sheet.total_height 82 83 @property 84 def selected_columns(self) -> list[ColumnInfo]: 85 """The sheet's selected columns""" 86 return self._sheet.selected_columns 87 88 def available_columns(self) -> list[ColumnInfo]: 89 """The columns available for the given sheet""" 90 return self._sheet.available_columns() 91 92 @property 93 def specified_dtypes(self) -> DTypeMap | None: 94 """The dtypes specified for the sheet""" 95 return self._sheet.specified_dtypes 96 97 @property 98 def visible(self) -> SheetVisible: 99 """The visibility of the sheet""" 100 return self._sheet.visible 101 102 def to_arrow(self) -> pa.RecordBatch: 103 """Converts the sheet to a pyarrow `RecordBatch` 104 105 Requires the `pyarrow` extra to be installed. 106 """ 107 if not _PYARROW_AVAILABLE: 108 raise ImportError( 109 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 110 ) 111 return self._sheet.to_arrow() 112 113 def to_arrow_with_errors(self) -> tuple[pa.RecordBatch, CellErrors | None]: 114 """Converts the sheet to a pyarrow `RecordBatch` with error information. 115 116 Stores the positions of any values that cannot be parsed as the specified type and were 117 therefore converted to None. 118 119 Requires the `pyarrow` extra to be installed. 120 """ 121 if not _PYARROW_AVAILABLE: 122 raise ImportError( 123 "pyarrow is required for to_arrow_with_errors(). Install with: pip install 'fastexcel[pyarrow]'" # noqa: E501 124 ) 125 rb, cell_errors = self._sheet.to_arrow_with_errors() 126 if not cell_errors.errors: 127 return (rb, None) 128 return (rb, cell_errors) 129 130 def to_pandas(self) -> pd.DataFrame: 131 """Converts the sheet to a Pandas `DataFrame`. 132 133 Requires the `pandas` extra to be installed. 134 """ 135 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 136 # which we don't implement. Using pyarrow conversion for now. 137 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 138 return self.to_arrow().to_pandas() 139 140 def to_polars(self) -> pl.DataFrame: 141 """Converts the sheet to a Polars `DataFrame`. 142 143 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 144 Requires the `polars` extra to be installed. 145 """ 146 import polars as pl 147 148 return pl.DataFrame(self) 149 150 def __arrow_c_schema__(self) -> object: 151 """Export the schema as an `ArrowSchema` `PyCapsule`. 152 153 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowschema-export 154 155 The Arrow PyCapsule Interface enables zero-copy data exchange with 156 Arrow-compatible libraries without requiring PyArrow as a dependency. 157 """ 158 return self._sheet.__arrow_c_schema__() 159 160 def __arrow_c_array__(self, requested_schema: object | None = None) -> tuple[object, object]: 161 """Export the schema and data as a pair of `ArrowSchema` and `ArrowArray` `PyCapsules`. 162 163 The optional `requested_schema` parameter allows for potential schema conversion. 164 165 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowarray-export 166 167 The Arrow PyCapsule Interface enables zero-copy data exchange with 168 Arrow-compatible libraries without requiring PyArrow as a dependency. 169 """ 170 return self._sheet.__arrow_c_array__(requested_schema) 171 172 def __repr__(self) -> str: 173 return self._sheet.__repr__() 174 175 176class ExcelTable: 177 """A class representing a single table in an Excel file""" 178 179 def __init__(self, table: _ExcelTable) -> None: 180 self._table = table 181 182 @property 183 def name(self) -> str: 184 """The name of the table""" 185 return self._table.name 186 187 @property 188 def sheet_name(self) -> str: 189 """The name of the sheet this table belongs to""" 190 return self._table.sheet_name 191 192 @property 193 def width(self) -> int: 194 """The table's width""" 195 return self._table.width 196 197 @property 198 def height(self) -> int: 199 """The table's height""" 200 return self._table.height 201 202 @property 203 def total_height(self) -> int: 204 """The table's total height""" 205 return self._table.total_height 206 207 @property 208 def offset(self) -> int: 209 """The table's offset before data starts""" 210 return self._table.offset 211 212 @property 213 def selected_columns(self) -> list[ColumnInfo]: 214 """The table's selected columns""" 215 return self._table.selected_columns 216 217 def available_columns(self) -> list[ColumnInfo]: 218 """The columns available for the given table""" 219 return self._table.available_columns() 220 221 @property 222 def specified_dtypes(self) -> DTypeMap | None: 223 """The dtypes specified for the table""" 224 return self._table.specified_dtypes 225 226 def to_arrow(self) -> pa.RecordBatch: 227 """Converts the table to a pyarrow `RecordBatch` 228 229 Requires the `pyarrow` extra to be installed. 230 """ 231 if not _PYARROW_AVAILABLE: 232 raise ImportError( 233 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 234 ) 235 return self._table.to_arrow() 236 237 def to_pandas(self) -> pd.DataFrame: 238 """Converts the table to a Pandas `DataFrame`. 239 240 Requires the `pandas` extra to be installed. 241 """ 242 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 243 # which we don't implement. Using pyarrow conversion for now. 244 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 245 return self.to_arrow().to_pandas() 246 247 def to_polars(self) -> pl.DataFrame: 248 """Converts the table to a Polars `DataFrame`. 249 250 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 251 Requires the `polars` extra to be installed. 252 """ 253 import polars as pl 254 255 return pl.DataFrame(self) 256 257 def __arrow_c_schema__(self) -> object: 258 """Export the schema as an `ArrowSchema` `PyCapsule`. 259 260 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowschema-export 261 262 The Arrow PyCapsule Interface enables zero-copy data exchange with 263 Arrow-compatible libraries without requiring PyArrow as a dependency. 264 """ 265 return self._table.__arrow_c_schema__() 266 267 def __arrow_c_array__(self, requested_schema: object | None = None) -> tuple[object, object]: 268 """Export the schema and data as a pair of `ArrowSchema` and `ArrowArray` `PyCapsules`. 269 270 The optional `requested_schema` parameter allows for potential schema conversion. 271 272 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowarray-export 273 274 The Arrow PyCapsule Interface enables zero-copy data exchange with 275 Arrow-compatible libraries without requiring PyArrow as a dependency. 276 """ 277 return self._table.__arrow_c_array__(requested_schema) 278 279 280class ExcelReader: 281 """A class representing an open Excel file and allowing to read its sheets""" 282 283 def __init__(self, reader: _ExcelReader) -> None: 284 self._reader = reader 285 286 @property 287 def sheet_names(self) -> list[str]: 288 """The list of sheet names""" 289 return self._reader.sheet_names 290 291 @typing.overload 292 def load_sheet( 293 self, 294 idx_or_name: int | str, 295 *, 296 header_row: int | None = 0, 297 column_names: list[str] | None = None, 298 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 299 n_rows: int | None = None, 300 schema_sample_rows: int | None = 1_000, 301 dtype_coercion: Literal["coerce", "strict"] = "coerce", 302 use_columns: list[str] 303 | list[int] 304 | str 305 | Callable[[ColumnInfoNoDtype], bool] 306 | None = None, 307 dtypes: DType | DTypeMap | None = None, 308 eager: Literal[False] = ..., 309 skip_whitespace_tail_rows: bool = False, 310 whitespace_as_null: bool = False, 311 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 312 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 313 ) -> ExcelSheet: ... 314 315 @typing.overload 316 def load_sheet( 317 self, 318 idx_or_name: int | str, 319 *, 320 header_row: int | None = 0, 321 column_names: list[str] | None = None, 322 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 323 n_rows: int | None = None, 324 schema_sample_rows: int | None = 1_000, 325 dtype_coercion: Literal["coerce", "strict"] = "coerce", 326 use_columns: list[str] 327 | list[int] 328 | str 329 | Callable[[ColumnInfoNoDtype], bool] 330 | None = None, 331 dtypes: DType | DTypeMap | None = None, 332 eager: Literal[True] = ..., 333 skip_whitespace_tail_rows: bool = False, 334 whitespace_as_null: bool = False, 335 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 336 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 337 ) -> pa.RecordBatch: ... 338 339 def load_sheet( 340 self, 341 idx_or_name: int | str, 342 *, 343 header_row: int | None = 0, 344 column_names: list[str] | None = None, 345 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 346 n_rows: int | None = None, 347 schema_sample_rows: int | None = 1_000, 348 dtype_coercion: Literal["coerce", "strict"] = "coerce", 349 use_columns: list[str] 350 | list[int] 351 | str 352 | Callable[[ColumnInfoNoDtype], bool] 353 | None = None, 354 dtypes: DType | DTypeMap | None = None, 355 eager: bool = False, 356 skip_whitespace_tail_rows: bool = False, 357 whitespace_as_null: bool = False, 358 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 359 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 360 ) -> ExcelSheet | pa.RecordBatch: 361 """Loads a sheet by index or name. 362 363 Column naming: 364 365 - Unnamed columns (missing header cell, `header_row=None`, or not covered by 366 `column_names`) are named `{unnamed_column_prefix}{idx}`, where `idx` is the column's 367 position within the loaded data range, not its absolute index in the sheet. 368 - Duplicate names are renamed `{name}{duplicate_column_separator}{n}`, with `n` starting 369 at 1 and incremented until the name doesn't match any column to its left. For example, 370 `a, a, a_1` becomes `a, a_1, a_1_1`. 371 - Generated names and names given through `column_names` are deduplicated the same way. 372 - Column names in `use_columns` and in a by-name `dtypes` map refer to the final, 373 deduplicated names. Exception: for tables loaded with their own header (no `header_row` 374 and no `column_names`), names in `use_columns` refer to the table's header names. 375 376 :param idx_or_name: The index (starting at 0) or the name of the sheet to load. 377 :param header_row: The index of the row containing the column labels, default index is 0. 378 If `None`, the sheet does not have any column labels. 379 Any rows before the `header_row` will be automatically skipped. 380 :param column_names: Overrides headers found in the document. 381 If `column_names` is used, `header_row` will be ignored. 382 :param n_rows: Specifies how many rows should be loaded. 383 If `None`, all rows are loaded 384 :param skip_rows: Specifies which rows should be skipped after the `header_row`. 385 Any rows before the `header_row` are automatically skipped. 386 It means row indices are relative to data rows, not the sheet! 387 Can be one of: 388 - `int`: Skip this many rows after the header row 389 - `list[int]`: Skip specific row indices (0-based relative to data rows) 390 - `Callable[[int], bool]`: Function that receives row index (0-based 391 relative to data rows) and returns True to skip the row 392 - `None`: If `header_row` is None, skips empty rows at beginning 393 :param schema_sample_rows: Specifies how many rows should be used to determine 394 the dtype of a column. Cannot be 0. A specific dtype can be 395 enforced for some or all columns through the `dtypes` parameter. 396 If `None`, all rows will be used. 397 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 398 will try to coerce different dtypes in a column to the same one, 399 whereas `strict` will raise an error in case a column contains 400 several dtypes. Note that this only applies to columns whose dtype 401 is guessed, i.e. not specified via `dtypes`. 402 :param use_columns: Specifies the columns to use. Can either be: 403 - `None` to select all columns 404 - A list of strings and ints, the column names and/or indices 405 (starting at 0) 406 - A string, a comma separated list of Excel column letters and column 407 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 408 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 409 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 410 ranges (e.g. `":C"` to select columns from A to C). These can be 411 combined for "except" patterns (e.g. `":C,E:"` to select everything 412 except column D) 413 - A callable, a function that takes a column and returns a boolean 414 indicating whether the column should be used 415 :param dtypes: An optional dtype (for all columns) 416 or dict of dtypes with keys as column indices or names. 417 :param eager: Specifies whether the sheet should be loaded eagerly. 418 `False` (default) will load the sheet lazily using the `PyCapsule` interface, 419 whereas `True` will load it eagerly via `pyarrow`. 420 421 Eager loading requires the `pyarrow` extra to be installed. 422 :param skip_whitespace_tail_rows: Skip rows at the end of the sheet 423 containing only whitespace and null values. 424 :param whitespace_as_null: Consider cells containing only whitespace as null values. 425 :param duplicate_column_separator: Separator between a duplicate column's name and its 426 counter. See "Column naming" above. 427 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 428 "Column naming" above. 429 """ 430 sheet_or_rb = self._reader.load_sheet( 431 idx_or_name=idx_or_name, 432 header_row=header_row, 433 column_names=column_names, 434 skip_rows=skip_rows, 435 n_rows=n_rows, 436 schema_sample_rows=schema_sample_rows, 437 dtype_coercion=dtype_coercion, 438 use_columns=use_columns, 439 dtypes=dtypes, 440 eager=eager, 441 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 442 whitespace_as_null=whitespace_as_null, 443 duplicate_column_separator=duplicate_column_separator, 444 unnamed_column_prefix=unnamed_column_prefix, 445 ) 446 return sheet_or_rb if eager else ExcelSheet(sheet_or_rb) 447 448 def table_names(self, sheet_name: str | None = None) -> list[str]: 449 """The list of table names. 450 451 Will return an empty list if no tables are found. 452 453 :param sheet_name: If given, will limit the list to the given sheet, will be faster 454 too. 455 """ 456 return self._reader.table_names(sheet_name) 457 458 def defined_names(self) -> list[DefinedName]: 459 """The list of defined names (named ranges) in the workbook. 460 461 Returns a list of DefinedName objects with 'name' and 'formula' attributes. 462 The formula is a string representation of the range or expression. 463 464 Will return an empty list if no defined names are found. 465 """ 466 return self._reader.defined_names() 467 468 def workbook_properties(self) -> WorkbookProperties: 469 """The document properties of the workbook, such as its creator, title and dates. 470 471 Supported for xlsx, xlsb, xls and ods files. Properties missing from the file are 472 `None`. `created` and `modified` are timezone-aware when the file stores a UTC 473 offset (as xlsx, xlsb and xls files usually do) and naive otherwise (as in ods 474 files). A date stored without a time is read as midnight. Custom property values 475 are returned as the text stored in the file. 476 """ 477 return self._reader.workbook_properties() 478 479 @typing.overload 480 def load_table( 481 self, 482 name: str, 483 *, 484 header_row: int | None = None, 485 column_names: list[str] | None = None, 486 skip_rows: int | None = None, 487 n_rows: int | None = None, 488 schema_sample_rows: int | None = 1_000, 489 dtype_coercion: Literal["coerce", "strict"] = "coerce", 490 use_columns: list[str] 491 | list[int] 492 | str 493 | Callable[[ColumnInfoNoDtype], bool] 494 | None = None, 495 dtypes: DType | DTypeMap | None = None, 496 eager: Literal[False] = ..., 497 skip_whitespace_tail_rows: bool = False, 498 whitespace_as_null: bool = False, 499 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 500 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 501 ) -> ExcelTable: ... 502 503 @typing.overload 504 def load_table( 505 self, 506 name: str, 507 *, 508 header_row: int | None = None, 509 column_names: list[str] | None = None, 510 skip_rows: int | None = None, 511 n_rows: int | None = None, 512 schema_sample_rows: int | None = 1_000, 513 dtype_coercion: Literal["coerce", "strict"] = "coerce", 514 use_columns: list[str] 515 | list[int] 516 | str 517 | Callable[[ColumnInfoNoDtype], bool] 518 | None = None, 519 dtypes: DType | DTypeMap | None = None, 520 eager: Literal[True] = ..., 521 skip_whitespace_tail_rows: bool = False, 522 whitespace_as_null: bool = False, 523 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 524 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 525 ) -> pa.RecordBatch: ... 526 527 def load_table( 528 self, 529 name: str, 530 *, 531 header_row: int | None = None, 532 column_names: list[str] | None = None, 533 skip_rows: int | None = None, 534 n_rows: int | None = None, 535 schema_sample_rows: int | None = 1_000, 536 dtype_coercion: Literal["coerce", "strict"] = "coerce", 537 use_columns: list[str] 538 | list[int] 539 | str 540 | Callable[[ColumnInfoNoDtype], bool] 541 | None = None, 542 dtypes: DType | DTypeMap | None = None, 543 eager: bool = False, 544 skip_whitespace_tail_rows: bool = False, 545 whitespace_as_null: bool = False, 546 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 547 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 548 ) -> ExcelTable | pa.RecordBatch: 549 """Loads a table by name. 550 551 :param name: The name of the table to load. 552 :param header_row: The index of the row containing the column labels. 553 If `None`, the table's column names will be used. 554 Any rows before the `header_row` will be automatically skipped. 555 :param column_names: Overrides headers found in the document. 556 If `column_names` is used, `header_row` will be ignored. 557 :param n_rows: Specifies how many rows should be loaded. 558 If `None`, all rows are loaded 559 :param skip_rows: Specifies how many rows should be skipped after the `header_row`. 560 Any rows before the `header_row` are automatically skipped. 561 If `header_row` is `None`, it skips the number of rows from the 562 start of the sheet. 563 :param schema_sample_rows: Specifies how many rows should be used to determine 564 the dtype of a column. Cannot be 0. A specific dtype can be 565 enforced for some or all columns through the `dtypes` parameter. 566 If `None`, all rows will be used. 567 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 568 will try to coerce different dtypes in a column to the same one, 569 whereas `strict` will raise an error in case a column contains 570 several dtypes. Note that this only applies to columns whose dtype 571 is guessed, i.e. not specified via `dtypes`. 572 :param use_columns: Specifies the columns to use. Can either be: 573 - `None` to select all columns 574 - A list of strings and ints, the column names and/or indices 575 (starting at 0) 576 - A string, a comma separated list of Excel column letters and column 577 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 578 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 579 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 580 ranges (e.g. `":C"` to select columns from A to C). These can be 581 combined for "except" patterns (e.g. `":C,E:"` to select everything 582 except column D) 583 - A callable, a function that takes a column and returns a boolean 584 indicating whether the column should be used 585 :param dtypes: An optional dtype (for all columns) 586 or dict of dtypes with keys as column indices or names. 587 :param eager: Specifies whether the table should be loaded eagerly. 588 `False` (default) will load the table lazily using the `PyCapsule` interface, 589 whereas `True` will load it eagerly via `pyarrow`. 590 591 Eager loading requires the `pyarrow` extra to be installed. 592 :param skip_whitespace_tail_rows: Skip rows at the end of the table 593 containing only whitespace and null values. 594 :param whitespace_as_null: Consider cells containing only whitespace as null values. 595 :param duplicate_column_separator: Separator between a duplicate column's name and its 596 counter. See "Column naming" in `load_sheet`. 597 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 598 "Column naming" in `load_sheet`. 599 """ 600 if eager: 601 return self._reader.load_table( 602 name=name, 603 header_row=header_row, 604 column_names=column_names, 605 skip_rows=skip_rows, 606 n_rows=n_rows, 607 schema_sample_rows=schema_sample_rows, 608 dtype_coercion=dtype_coercion, 609 use_columns=use_columns, 610 dtypes=dtypes, 611 eager=True, 612 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 613 whitespace_as_null=whitespace_as_null, 614 duplicate_column_separator=duplicate_column_separator, 615 unnamed_column_prefix=unnamed_column_prefix, 616 ) 617 else: 618 return ExcelTable( 619 self._reader.load_table( 620 name=name, 621 header_row=header_row, 622 column_names=column_names, 623 skip_rows=skip_rows, 624 n_rows=n_rows, 625 schema_sample_rows=schema_sample_rows, 626 dtype_coercion=dtype_coercion, 627 use_columns=use_columns, 628 dtypes=dtypes, 629 eager=False, 630 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 631 whitespace_as_null=whitespace_as_null, 632 duplicate_column_separator=duplicate_column_separator, 633 unnamed_column_prefix=unnamed_column_prefix, 634 ) 635 ) 636 637 def load_sheet_eager( 638 self, 639 idx_or_name: int | str, 640 *, 641 header_row: int | None = 0, 642 column_names: list[str] | None = None, 643 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 644 n_rows: int | None = None, 645 schema_sample_rows: int | None = 1_000, 646 dtype_coercion: Literal["coerce", "strict"] = "coerce", 647 use_columns: list[str] | list[int] | str | None = None, 648 dtypes: DType | DTypeMap | None = None, 649 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 650 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 651 ) -> pa.RecordBatch: 652 """Loads a sheet eagerly by index or name. 653 654 For xlsx files, this will be faster and more memory-efficient, as it will use 655 `worksheet_range_ref` under the hood, which returns borrowed types. 656 657 Refer to `load_sheet` for parameter documentation 658 659 Requires the `pyarrow` extra to be installed. 660 """ 661 return self._reader.load_sheet( 662 idx_or_name=idx_or_name, 663 header_row=header_row, 664 column_names=column_names, 665 skip_rows=skip_rows, 666 n_rows=n_rows, 667 schema_sample_rows=schema_sample_rows, 668 dtype_coercion=dtype_coercion, 669 use_columns=use_columns, 670 dtypes=dtypes, 671 eager=True, 672 duplicate_column_separator=duplicate_column_separator, 673 unnamed_column_prefix=unnamed_column_prefix, 674 ) 675 676 def load_sheet_by_name( 677 self, 678 name: str, 679 *, 680 header_row: int | None = 0, 681 column_names: list[str] | None = None, 682 skip_rows: int | None = None, 683 n_rows: int | None = None, 684 schema_sample_rows: int | None = 1_000, 685 dtype_coercion: Literal["coerce", "strict"] = "coerce", 686 use_columns: list[str] 687 | list[int] 688 | str 689 | Callable[[ColumnInfoNoDtype], bool] 690 | None = None, 691 dtypes: DType | DTypeMap | None = None, 692 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 693 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 694 ) -> ExcelSheet: 695 """Loads a sheet by name. 696 697 Refer to `load_sheet` for parameter documentation 698 """ 699 return self.load_sheet( 700 name, 701 header_row=header_row, 702 column_names=column_names, 703 skip_rows=skip_rows, 704 n_rows=n_rows, 705 schema_sample_rows=schema_sample_rows, 706 dtype_coercion=dtype_coercion, 707 use_columns=use_columns, 708 dtypes=dtypes, 709 duplicate_column_separator=duplicate_column_separator, 710 unnamed_column_prefix=unnamed_column_prefix, 711 ) 712 713 def load_sheet_by_idx( 714 self, 715 idx: int, 716 *, 717 header_row: int | None = 0, 718 column_names: list[str] | None = None, 719 skip_rows: int | None = None, 720 n_rows: int | None = None, 721 schema_sample_rows: int | None = 1_000, 722 dtype_coercion: Literal["coerce", "strict"] = "coerce", 723 use_columns: list[str] 724 | list[int] 725 | str 726 | Callable[[ColumnInfoNoDtype], bool] 727 | None = None, 728 dtypes: DType | DTypeMap | None = None, 729 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 730 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 731 ) -> ExcelSheet: 732 """Loads a sheet by index. 733 734 Refer to `load_sheet` for parameter documentation 735 """ 736 return self.load_sheet( 737 idx, 738 header_row=header_row, 739 column_names=column_names, 740 skip_rows=skip_rows, 741 n_rows=n_rows, 742 schema_sample_rows=schema_sample_rows, 743 dtype_coercion=dtype_coercion, 744 use_columns=use_columns, 745 dtypes=dtypes, 746 duplicate_column_separator=duplicate_column_separator, 747 unnamed_column_prefix=unnamed_column_prefix, 748 ) 749 750 def __repr__(self) -> str: 751 return self._reader.__repr__() 752 753 754def read_excel(source: Path | str | bytes) -> ExcelReader: 755 """Opens and loads an excel file. 756 757 :param source: The path to a file or its content as bytes 758 """ 759 if isinstance(source, str | Path): 760 source = expanduser(source) 761 return ExcelReader(_read_excel(source)) 762 763 764__all__ = ( 765 # version 766 "__version__", 767 # main entrypoint 768 "read_excel", 769 # Python types 770 "DType", 771 "DTypeMap", 772 # Column naming defaults 773 "DEFAULT_DUPLICATE_COLUMN_SEPARATOR", 774 "DEFAULT_UNNAMED_COLUMN_PREFIX", 775 # Excel reader 776 "ExcelReader", 777 # Excel sheet 778 "ExcelSheet", 779 # Excel table 780 "ExcelTable", 781 # Column metadata 782 "DTypeFrom", 783 "ColumnNameFrom", 784 "ColumnInfo", 785 # Defined names 786 "DefinedName", 787 # Workbook properties 788 "WorkbookProperties", 789 # Parse error information 790 "CellError", 791 "CellErrors", 792 # Exceptions 793 "FastExcelError", 794 "CannotRetrieveCellDataError", 795 "CalamineCellError", 796 "CalamineError", 797 "SheetNotFoundError", 798 "ColumnNotFoundError", 799 "ArrowError", 800 "InvalidParametersError", 801 "UnsupportedColumnTypeCombinationError", 802)
755def read_excel(source: Path | str | bytes) -> ExcelReader: 756 """Opens and loads an excel file. 757 758 :param source: The path to a file or its content as bytes 759 """ 760 if isinstance(source, str | Path): 761 source = expanduser(source) 762 return ExcelReader(_read_excel(source))
Opens and loads an excel file.
Parameters
- source: The path to a file or its content as bytes
281class ExcelReader: 282 """A class representing an open Excel file and allowing to read its sheets""" 283 284 def __init__(self, reader: _ExcelReader) -> None: 285 self._reader = reader 286 287 @property 288 def sheet_names(self) -> list[str]: 289 """The list of sheet names""" 290 return self._reader.sheet_names 291 292 @typing.overload 293 def load_sheet( 294 self, 295 idx_or_name: int | str, 296 *, 297 header_row: int | None = 0, 298 column_names: list[str] | None = None, 299 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 300 n_rows: int | None = None, 301 schema_sample_rows: int | None = 1_000, 302 dtype_coercion: Literal["coerce", "strict"] = "coerce", 303 use_columns: list[str] 304 | list[int] 305 | str 306 | Callable[[ColumnInfoNoDtype], bool] 307 | None = None, 308 dtypes: DType | DTypeMap | None = None, 309 eager: Literal[False] = ..., 310 skip_whitespace_tail_rows: bool = False, 311 whitespace_as_null: bool = False, 312 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 313 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 314 ) -> ExcelSheet: ... 315 316 @typing.overload 317 def load_sheet( 318 self, 319 idx_or_name: int | str, 320 *, 321 header_row: int | None = 0, 322 column_names: list[str] | None = None, 323 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 324 n_rows: int | None = None, 325 schema_sample_rows: int | None = 1_000, 326 dtype_coercion: Literal["coerce", "strict"] = "coerce", 327 use_columns: list[str] 328 | list[int] 329 | str 330 | Callable[[ColumnInfoNoDtype], bool] 331 | None = None, 332 dtypes: DType | DTypeMap | None = None, 333 eager: Literal[True] = ..., 334 skip_whitespace_tail_rows: bool = False, 335 whitespace_as_null: bool = False, 336 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 337 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 338 ) -> pa.RecordBatch: ... 339 340 def load_sheet( 341 self, 342 idx_or_name: int | str, 343 *, 344 header_row: int | None = 0, 345 column_names: list[str] | None = None, 346 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 347 n_rows: int | None = None, 348 schema_sample_rows: int | None = 1_000, 349 dtype_coercion: Literal["coerce", "strict"] = "coerce", 350 use_columns: list[str] 351 | list[int] 352 | str 353 | Callable[[ColumnInfoNoDtype], bool] 354 | None = None, 355 dtypes: DType | DTypeMap | None = None, 356 eager: bool = False, 357 skip_whitespace_tail_rows: bool = False, 358 whitespace_as_null: bool = False, 359 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 360 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 361 ) -> ExcelSheet | pa.RecordBatch: 362 """Loads a sheet by index or name. 363 364 Column naming: 365 366 - Unnamed columns (missing header cell, `header_row=None`, or not covered by 367 `column_names`) are named `{unnamed_column_prefix}{idx}`, where `idx` is the column's 368 position within the loaded data range, not its absolute index in the sheet. 369 - Duplicate names are renamed `{name}{duplicate_column_separator}{n}`, with `n` starting 370 at 1 and incremented until the name doesn't match any column to its left. For example, 371 `a, a, a_1` becomes `a, a_1, a_1_1`. 372 - Generated names and names given through `column_names` are deduplicated the same way. 373 - Column names in `use_columns` and in a by-name `dtypes` map refer to the final, 374 deduplicated names. Exception: for tables loaded with their own header (no `header_row` 375 and no `column_names`), names in `use_columns` refer to the table's header names. 376 377 :param idx_or_name: The index (starting at 0) or the name of the sheet to load. 378 :param header_row: The index of the row containing the column labels, default index is 0. 379 If `None`, the sheet does not have any column labels. 380 Any rows before the `header_row` will be automatically skipped. 381 :param column_names: Overrides headers found in the document. 382 If `column_names` is used, `header_row` will be ignored. 383 :param n_rows: Specifies how many rows should be loaded. 384 If `None`, all rows are loaded 385 :param skip_rows: Specifies which rows should be skipped after the `header_row`. 386 Any rows before the `header_row` are automatically skipped. 387 It means row indices are relative to data rows, not the sheet! 388 Can be one of: 389 - `int`: Skip this many rows after the header row 390 - `list[int]`: Skip specific row indices (0-based relative to data rows) 391 - `Callable[[int], bool]`: Function that receives row index (0-based 392 relative to data rows) and returns True to skip the row 393 - `None`: If `header_row` is None, skips empty rows at beginning 394 :param schema_sample_rows: Specifies how many rows should be used to determine 395 the dtype of a column. Cannot be 0. A specific dtype can be 396 enforced for some or all columns through the `dtypes` parameter. 397 If `None`, all rows will be used. 398 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 399 will try to coerce different dtypes in a column to the same one, 400 whereas `strict` will raise an error in case a column contains 401 several dtypes. Note that this only applies to columns whose dtype 402 is guessed, i.e. not specified via `dtypes`. 403 :param use_columns: Specifies the columns to use. Can either be: 404 - `None` to select all columns 405 - A list of strings and ints, the column names and/or indices 406 (starting at 0) 407 - A string, a comma separated list of Excel column letters and column 408 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 409 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 410 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 411 ranges (e.g. `":C"` to select columns from A to C). These can be 412 combined for "except" patterns (e.g. `":C,E:"` to select everything 413 except column D) 414 - A callable, a function that takes a column and returns a boolean 415 indicating whether the column should be used 416 :param dtypes: An optional dtype (for all columns) 417 or dict of dtypes with keys as column indices or names. 418 :param eager: Specifies whether the sheet should be loaded eagerly. 419 `False` (default) will load the sheet lazily using the `PyCapsule` interface, 420 whereas `True` will load it eagerly via `pyarrow`. 421 422 Eager loading requires the `pyarrow` extra to be installed. 423 :param skip_whitespace_tail_rows: Skip rows at the end of the sheet 424 containing only whitespace and null values. 425 :param whitespace_as_null: Consider cells containing only whitespace as null values. 426 :param duplicate_column_separator: Separator between a duplicate column's name and its 427 counter. See "Column naming" above. 428 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 429 "Column naming" above. 430 """ 431 sheet_or_rb = self._reader.load_sheet( 432 idx_or_name=idx_or_name, 433 header_row=header_row, 434 column_names=column_names, 435 skip_rows=skip_rows, 436 n_rows=n_rows, 437 schema_sample_rows=schema_sample_rows, 438 dtype_coercion=dtype_coercion, 439 use_columns=use_columns, 440 dtypes=dtypes, 441 eager=eager, 442 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 443 whitespace_as_null=whitespace_as_null, 444 duplicate_column_separator=duplicate_column_separator, 445 unnamed_column_prefix=unnamed_column_prefix, 446 ) 447 return sheet_or_rb if eager else ExcelSheet(sheet_or_rb) 448 449 def table_names(self, sheet_name: str | None = None) -> list[str]: 450 """The list of table names. 451 452 Will return an empty list if no tables are found. 453 454 :param sheet_name: If given, will limit the list to the given sheet, will be faster 455 too. 456 """ 457 return self._reader.table_names(sheet_name) 458 459 def defined_names(self) -> list[DefinedName]: 460 """The list of defined names (named ranges) in the workbook. 461 462 Returns a list of DefinedName objects with 'name' and 'formula' attributes. 463 The formula is a string representation of the range or expression. 464 465 Will return an empty list if no defined names are found. 466 """ 467 return self._reader.defined_names() 468 469 def workbook_properties(self) -> WorkbookProperties: 470 """The document properties of the workbook, such as its creator, title and dates. 471 472 Supported for xlsx, xlsb, xls and ods files. Properties missing from the file are 473 `None`. `created` and `modified` are timezone-aware when the file stores a UTC 474 offset (as xlsx, xlsb and xls files usually do) and naive otherwise (as in ods 475 files). A date stored without a time is read as midnight. Custom property values 476 are returned as the text stored in the file. 477 """ 478 return self._reader.workbook_properties() 479 480 @typing.overload 481 def load_table( 482 self, 483 name: str, 484 *, 485 header_row: int | None = None, 486 column_names: list[str] | None = None, 487 skip_rows: int | None = None, 488 n_rows: int | None = None, 489 schema_sample_rows: int | None = 1_000, 490 dtype_coercion: Literal["coerce", "strict"] = "coerce", 491 use_columns: list[str] 492 | list[int] 493 | str 494 | Callable[[ColumnInfoNoDtype], bool] 495 | None = None, 496 dtypes: DType | DTypeMap | None = None, 497 eager: Literal[False] = ..., 498 skip_whitespace_tail_rows: bool = False, 499 whitespace_as_null: bool = False, 500 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 501 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 502 ) -> ExcelTable: ... 503 504 @typing.overload 505 def load_table( 506 self, 507 name: str, 508 *, 509 header_row: int | None = None, 510 column_names: list[str] | None = None, 511 skip_rows: int | None = None, 512 n_rows: int | None = None, 513 schema_sample_rows: int | None = 1_000, 514 dtype_coercion: Literal["coerce", "strict"] = "coerce", 515 use_columns: list[str] 516 | list[int] 517 | str 518 | Callable[[ColumnInfoNoDtype], bool] 519 | None = None, 520 dtypes: DType | DTypeMap | None = None, 521 eager: Literal[True] = ..., 522 skip_whitespace_tail_rows: bool = False, 523 whitespace_as_null: bool = False, 524 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 525 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 526 ) -> pa.RecordBatch: ... 527 528 def load_table( 529 self, 530 name: str, 531 *, 532 header_row: int | None = None, 533 column_names: list[str] | None = None, 534 skip_rows: int | None = None, 535 n_rows: int | None = None, 536 schema_sample_rows: int | None = 1_000, 537 dtype_coercion: Literal["coerce", "strict"] = "coerce", 538 use_columns: list[str] 539 | list[int] 540 | str 541 | Callable[[ColumnInfoNoDtype], bool] 542 | None = None, 543 dtypes: DType | DTypeMap | None = None, 544 eager: bool = False, 545 skip_whitespace_tail_rows: bool = False, 546 whitespace_as_null: bool = False, 547 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 548 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 549 ) -> ExcelTable | pa.RecordBatch: 550 """Loads a table by name. 551 552 :param name: The name of the table to load. 553 :param header_row: The index of the row containing the column labels. 554 If `None`, the table's column names will be used. 555 Any rows before the `header_row` will be automatically skipped. 556 :param column_names: Overrides headers found in the document. 557 If `column_names` is used, `header_row` will be ignored. 558 :param n_rows: Specifies how many rows should be loaded. 559 If `None`, all rows are loaded 560 :param skip_rows: Specifies how many rows should be skipped after the `header_row`. 561 Any rows before the `header_row` are automatically skipped. 562 If `header_row` is `None`, it skips the number of rows from the 563 start of the sheet. 564 :param schema_sample_rows: Specifies how many rows should be used to determine 565 the dtype of a column. Cannot be 0. A specific dtype can be 566 enforced for some or all columns through the `dtypes` parameter. 567 If `None`, all rows will be used. 568 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 569 will try to coerce different dtypes in a column to the same one, 570 whereas `strict` will raise an error in case a column contains 571 several dtypes. Note that this only applies to columns whose dtype 572 is guessed, i.e. not specified via `dtypes`. 573 :param use_columns: Specifies the columns to use. Can either be: 574 - `None` to select all columns 575 - A list of strings and ints, the column names and/or indices 576 (starting at 0) 577 - A string, a comma separated list of Excel column letters and column 578 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 579 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 580 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 581 ranges (e.g. `":C"` to select columns from A to C). These can be 582 combined for "except" patterns (e.g. `":C,E:"` to select everything 583 except column D) 584 - A callable, a function that takes a column and returns a boolean 585 indicating whether the column should be used 586 :param dtypes: An optional dtype (for all columns) 587 or dict of dtypes with keys as column indices or names. 588 :param eager: Specifies whether the table should be loaded eagerly. 589 `False` (default) will load the table lazily using the `PyCapsule` interface, 590 whereas `True` will load it eagerly via `pyarrow`. 591 592 Eager loading requires the `pyarrow` extra to be installed. 593 :param skip_whitespace_tail_rows: Skip rows at the end of the table 594 containing only whitespace and null values. 595 :param whitespace_as_null: Consider cells containing only whitespace as null values. 596 :param duplicate_column_separator: Separator between a duplicate column's name and its 597 counter. See "Column naming" in `load_sheet`. 598 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 599 "Column naming" in `load_sheet`. 600 """ 601 if eager: 602 return self._reader.load_table( 603 name=name, 604 header_row=header_row, 605 column_names=column_names, 606 skip_rows=skip_rows, 607 n_rows=n_rows, 608 schema_sample_rows=schema_sample_rows, 609 dtype_coercion=dtype_coercion, 610 use_columns=use_columns, 611 dtypes=dtypes, 612 eager=True, 613 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 614 whitespace_as_null=whitespace_as_null, 615 duplicate_column_separator=duplicate_column_separator, 616 unnamed_column_prefix=unnamed_column_prefix, 617 ) 618 else: 619 return ExcelTable( 620 self._reader.load_table( 621 name=name, 622 header_row=header_row, 623 column_names=column_names, 624 skip_rows=skip_rows, 625 n_rows=n_rows, 626 schema_sample_rows=schema_sample_rows, 627 dtype_coercion=dtype_coercion, 628 use_columns=use_columns, 629 dtypes=dtypes, 630 eager=False, 631 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 632 whitespace_as_null=whitespace_as_null, 633 duplicate_column_separator=duplicate_column_separator, 634 unnamed_column_prefix=unnamed_column_prefix, 635 ) 636 ) 637 638 def load_sheet_eager( 639 self, 640 idx_or_name: int | str, 641 *, 642 header_row: int | None = 0, 643 column_names: list[str] | None = None, 644 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 645 n_rows: int | None = None, 646 schema_sample_rows: int | None = 1_000, 647 dtype_coercion: Literal["coerce", "strict"] = "coerce", 648 use_columns: list[str] | list[int] | str | None = None, 649 dtypes: DType | DTypeMap | None = None, 650 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 651 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 652 ) -> pa.RecordBatch: 653 """Loads a sheet eagerly by index or name. 654 655 For xlsx files, this will be faster and more memory-efficient, as it will use 656 `worksheet_range_ref` under the hood, which returns borrowed types. 657 658 Refer to `load_sheet` for parameter documentation 659 660 Requires the `pyarrow` extra to be installed. 661 """ 662 return self._reader.load_sheet( 663 idx_or_name=idx_or_name, 664 header_row=header_row, 665 column_names=column_names, 666 skip_rows=skip_rows, 667 n_rows=n_rows, 668 schema_sample_rows=schema_sample_rows, 669 dtype_coercion=dtype_coercion, 670 use_columns=use_columns, 671 dtypes=dtypes, 672 eager=True, 673 duplicate_column_separator=duplicate_column_separator, 674 unnamed_column_prefix=unnamed_column_prefix, 675 ) 676 677 def load_sheet_by_name( 678 self, 679 name: str, 680 *, 681 header_row: int | None = 0, 682 column_names: list[str] | None = None, 683 skip_rows: int | None = None, 684 n_rows: int | None = None, 685 schema_sample_rows: int | None = 1_000, 686 dtype_coercion: Literal["coerce", "strict"] = "coerce", 687 use_columns: list[str] 688 | list[int] 689 | str 690 | Callable[[ColumnInfoNoDtype], bool] 691 | None = None, 692 dtypes: DType | DTypeMap | None = None, 693 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 694 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 695 ) -> ExcelSheet: 696 """Loads a sheet by name. 697 698 Refer to `load_sheet` for parameter documentation 699 """ 700 return self.load_sheet( 701 name, 702 header_row=header_row, 703 column_names=column_names, 704 skip_rows=skip_rows, 705 n_rows=n_rows, 706 schema_sample_rows=schema_sample_rows, 707 dtype_coercion=dtype_coercion, 708 use_columns=use_columns, 709 dtypes=dtypes, 710 duplicate_column_separator=duplicate_column_separator, 711 unnamed_column_prefix=unnamed_column_prefix, 712 ) 713 714 def load_sheet_by_idx( 715 self, 716 idx: int, 717 *, 718 header_row: int | None = 0, 719 column_names: list[str] | None = None, 720 skip_rows: int | None = None, 721 n_rows: int | None = None, 722 schema_sample_rows: int | None = 1_000, 723 dtype_coercion: Literal["coerce", "strict"] = "coerce", 724 use_columns: list[str] 725 | list[int] 726 | str 727 | Callable[[ColumnInfoNoDtype], bool] 728 | None = None, 729 dtypes: DType | DTypeMap | None = None, 730 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 731 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 732 ) -> ExcelSheet: 733 """Loads a sheet by index. 734 735 Refer to `load_sheet` for parameter documentation 736 """ 737 return self.load_sheet( 738 idx, 739 header_row=header_row, 740 column_names=column_names, 741 skip_rows=skip_rows, 742 n_rows=n_rows, 743 schema_sample_rows=schema_sample_rows, 744 dtype_coercion=dtype_coercion, 745 use_columns=use_columns, 746 dtypes=dtypes, 747 duplicate_column_separator=duplicate_column_separator, 748 unnamed_column_prefix=unnamed_column_prefix, 749 ) 750 751 def __repr__(self) -> str: 752 return self._reader.__repr__()
A class representing an open Excel file and allowing to read its sheets
287 @property 288 def sheet_names(self) -> list[str]: 289 """The list of sheet names""" 290 return self._reader.sheet_names
The list of sheet names
340 def load_sheet( 341 self, 342 idx_or_name: int | str, 343 *, 344 header_row: int | None = 0, 345 column_names: list[str] | None = None, 346 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 347 n_rows: int | None = None, 348 schema_sample_rows: int | None = 1_000, 349 dtype_coercion: Literal["coerce", "strict"] = "coerce", 350 use_columns: list[str] 351 | list[int] 352 | str 353 | Callable[[ColumnInfoNoDtype], bool] 354 | None = None, 355 dtypes: DType | DTypeMap | None = None, 356 eager: bool = False, 357 skip_whitespace_tail_rows: bool = False, 358 whitespace_as_null: bool = False, 359 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 360 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 361 ) -> ExcelSheet | pa.RecordBatch: 362 """Loads a sheet by index or name. 363 364 Column naming: 365 366 - Unnamed columns (missing header cell, `header_row=None`, or not covered by 367 `column_names`) are named `{unnamed_column_prefix}{idx}`, where `idx` is the column's 368 position within the loaded data range, not its absolute index in the sheet. 369 - Duplicate names are renamed `{name}{duplicate_column_separator}{n}`, with `n` starting 370 at 1 and incremented until the name doesn't match any column to its left. For example, 371 `a, a, a_1` becomes `a, a_1, a_1_1`. 372 - Generated names and names given through `column_names` are deduplicated the same way. 373 - Column names in `use_columns` and in a by-name `dtypes` map refer to the final, 374 deduplicated names. Exception: for tables loaded with their own header (no `header_row` 375 and no `column_names`), names in `use_columns` refer to the table's header names. 376 377 :param idx_or_name: The index (starting at 0) or the name of the sheet to load. 378 :param header_row: The index of the row containing the column labels, default index is 0. 379 If `None`, the sheet does not have any column labels. 380 Any rows before the `header_row` will be automatically skipped. 381 :param column_names: Overrides headers found in the document. 382 If `column_names` is used, `header_row` will be ignored. 383 :param n_rows: Specifies how many rows should be loaded. 384 If `None`, all rows are loaded 385 :param skip_rows: Specifies which rows should be skipped after the `header_row`. 386 Any rows before the `header_row` are automatically skipped. 387 It means row indices are relative to data rows, not the sheet! 388 Can be one of: 389 - `int`: Skip this many rows after the header row 390 - `list[int]`: Skip specific row indices (0-based relative to data rows) 391 - `Callable[[int], bool]`: Function that receives row index (0-based 392 relative to data rows) and returns True to skip the row 393 - `None`: If `header_row` is None, skips empty rows at beginning 394 :param schema_sample_rows: Specifies how many rows should be used to determine 395 the dtype of a column. Cannot be 0. A specific dtype can be 396 enforced for some or all columns through the `dtypes` parameter. 397 If `None`, all rows will be used. 398 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 399 will try to coerce different dtypes in a column to the same one, 400 whereas `strict` will raise an error in case a column contains 401 several dtypes. Note that this only applies to columns whose dtype 402 is guessed, i.e. not specified via `dtypes`. 403 :param use_columns: Specifies the columns to use. Can either be: 404 - `None` to select all columns 405 - A list of strings and ints, the column names and/or indices 406 (starting at 0) 407 - A string, a comma separated list of Excel column letters and column 408 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 409 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 410 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 411 ranges (e.g. `":C"` to select columns from A to C). These can be 412 combined for "except" patterns (e.g. `":C,E:"` to select everything 413 except column D) 414 - A callable, a function that takes a column and returns a boolean 415 indicating whether the column should be used 416 :param dtypes: An optional dtype (for all columns) 417 or dict of dtypes with keys as column indices or names. 418 :param eager: Specifies whether the sheet should be loaded eagerly. 419 `False` (default) will load the sheet lazily using the `PyCapsule` interface, 420 whereas `True` will load it eagerly via `pyarrow`. 421 422 Eager loading requires the `pyarrow` extra to be installed. 423 :param skip_whitespace_tail_rows: Skip rows at the end of the sheet 424 containing only whitespace and null values. 425 :param whitespace_as_null: Consider cells containing only whitespace as null values. 426 :param duplicate_column_separator: Separator between a duplicate column's name and its 427 counter. See "Column naming" above. 428 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 429 "Column naming" above. 430 """ 431 sheet_or_rb = self._reader.load_sheet( 432 idx_or_name=idx_or_name, 433 header_row=header_row, 434 column_names=column_names, 435 skip_rows=skip_rows, 436 n_rows=n_rows, 437 schema_sample_rows=schema_sample_rows, 438 dtype_coercion=dtype_coercion, 439 use_columns=use_columns, 440 dtypes=dtypes, 441 eager=eager, 442 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 443 whitespace_as_null=whitespace_as_null, 444 duplicate_column_separator=duplicate_column_separator, 445 unnamed_column_prefix=unnamed_column_prefix, 446 ) 447 return sheet_or_rb if eager else ExcelSheet(sheet_or_rb)
Loads a sheet by index or name.
Column naming:
- Unnamed columns (missing header cell,
header_row=None, or not covered bycolumn_names) are named{unnamed_column_prefix}{idx}, whereidxis the column's position within the loaded data range, not its absolute index in the sheet. - Duplicate names are renamed
{name}{duplicate_column_separator}{n}, withnstarting at 1 and incremented until the name doesn't match any column to its left. For example,a, a, a_1becomesa, a_1, a_1_1. - Generated names and names given through
column_namesare deduplicated the same way. - Column names in
use_columnsand in a by-namedtypesmap refer to the final, deduplicated names. Exception: for tables loaded with their own header (noheader_rowand nocolumn_names), names inuse_columnsrefer to the table's header names.
Parameters
- idx_or_name: The index (starting at 0) or the name of the sheet to load.
- header_row: The index of the row containing the column labels, default index is 0.
If
None, the sheet does not have any column labels. Any rows before theheader_rowwill be automatically skipped. - column_names: Overrides headers found in the document.
If
column_namesis used,header_rowwill be ignored. - n_rows: Specifies how many rows should be loaded.
If
None, all rows are loaded - skip_rows: Specifies which rows should be skipped after the
header_row. Any rows before theheader_roware automatically skipped. It means row indices are relative to data rows, not the sheet! Can be one of:int: Skip this many rows after the header rowlist[int]: Skip specific row indices (0-based relative to data rows)Callable[[int], bool]: Function that receives row index (0-based relative to data rows) and returns True to skip the rowNone: Ifheader_rowis None, skips empty rows at beginning
- schema_sample_rows: Specifies how many rows should be used to determine
the dtype of a column. Cannot be 0. A specific dtype can be
enforced for some or all columns through the
dtypesparameter. IfNone, all rows will be used. - dtype_coercion: Specifies how type coercion should behave.
coerce(the default) will try to coerce different dtypes in a column to the same one, whereasstrictwill raise an error in case a column contains several dtypes. Note that this only applies to columns whose dtype is guessed, i.e. not specified viadtypes. - use_columns: Specifies the columns to use. Can either be:
Noneto select all columns- A list of strings and ints, the column names and/or indices (starting at 0)
- A string, a comma separated list of Excel column letters and column
ranges (e.g.
"A:E"or"A,C,E:F", which would result inA,B,C,D,EandA,C,E,F). Also supports open-ended ranges (e.g."B:"to select all columns from B onwards) and from-beginning ranges (e.g.":C"to select columns from A to C). These can be combined for "except" patterns (e.g.":C,E:"to select everything except column D) - A callable, a function that takes a column and returns a boolean indicating whether the column should be used
- dtypes: An optional dtype (for all columns) or dict of dtypes with keys as column indices or names.
eager: Specifies whether the sheet should be loaded eagerly.
False(default) will load the sheet lazily using thePyCapsuleinterface, whereasTruewill load it eagerly viapyarrow.Eager loading requires the `pyarrow` extra to be installed.- skip_whitespace_tail_rows: Skip rows at the end of the sheet containing only whitespace and null values.
- whitespace_as_null: Consider cells containing only whitespace as null values.
- duplicate_column_separator: Separator between a duplicate column's name and its counter. See "Column naming" above.
- unnamed_column_prefix: Prefix of generated names for unnamed columns. See "Column naming" above.
449 def table_names(self, sheet_name: str | None = None) -> list[str]: 450 """The list of table names. 451 452 Will return an empty list if no tables are found. 453 454 :param sheet_name: If given, will limit the list to the given sheet, will be faster 455 too. 456 """ 457 return self._reader.table_names(sheet_name)
The list of table names.
Will return an empty list if no tables are found.
Parameters
- sheet_name: If given, will limit the list to the given sheet, will be faster too.
459 def defined_names(self) -> list[DefinedName]: 460 """The list of defined names (named ranges) in the workbook. 461 462 Returns a list of DefinedName objects with 'name' and 'formula' attributes. 463 The formula is a string representation of the range or expression. 464 465 Will return an empty list if no defined names are found. 466 """ 467 return self._reader.defined_names()
The list of defined names (named ranges) in the workbook.
Returns a list of DefinedName objects with 'name' and 'formula' attributes. The formula is a string representation of the range or expression.
Will return an empty list if no defined names are found.
469 def workbook_properties(self) -> WorkbookProperties: 470 """The document properties of the workbook, such as its creator, title and dates. 471 472 Supported for xlsx, xlsb, xls and ods files. Properties missing from the file are 473 `None`. `created` and `modified` are timezone-aware when the file stores a UTC 474 offset (as xlsx, xlsb and xls files usually do) and naive otherwise (as in ods 475 files). A date stored without a time is read as midnight. Custom property values 476 are returned as the text stored in the file. 477 """ 478 return self._reader.workbook_properties()
The document properties of the workbook, such as its creator, title and dates.
Supported for xlsx, xlsb, xls and ods files. Properties missing from the file are
None. created and modified are timezone-aware when the file stores a UTC
offset (as xlsx, xlsb and xls files usually do) and naive otherwise (as in ods
files). A date stored without a time is read as midnight. Custom property values
are returned as the text stored in the file.
528 def load_table( 529 self, 530 name: str, 531 *, 532 header_row: int | None = None, 533 column_names: list[str] | None = None, 534 skip_rows: int | None = None, 535 n_rows: int | None = None, 536 schema_sample_rows: int | None = 1_000, 537 dtype_coercion: Literal["coerce", "strict"] = "coerce", 538 use_columns: list[str] 539 | list[int] 540 | str 541 | Callable[[ColumnInfoNoDtype], bool] 542 | None = None, 543 dtypes: DType | DTypeMap | None = None, 544 eager: bool = False, 545 skip_whitespace_tail_rows: bool = False, 546 whitespace_as_null: bool = False, 547 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 548 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 549 ) -> ExcelTable | pa.RecordBatch: 550 """Loads a table by name. 551 552 :param name: The name of the table to load. 553 :param header_row: The index of the row containing the column labels. 554 If `None`, the table's column names will be used. 555 Any rows before the `header_row` will be automatically skipped. 556 :param column_names: Overrides headers found in the document. 557 If `column_names` is used, `header_row` will be ignored. 558 :param n_rows: Specifies how many rows should be loaded. 559 If `None`, all rows are loaded 560 :param skip_rows: Specifies how many rows should be skipped after the `header_row`. 561 Any rows before the `header_row` are automatically skipped. 562 If `header_row` is `None`, it skips the number of rows from the 563 start of the sheet. 564 :param schema_sample_rows: Specifies how many rows should be used to determine 565 the dtype of a column. Cannot be 0. A specific dtype can be 566 enforced for some or all columns through the `dtypes` parameter. 567 If `None`, all rows will be used. 568 :param dtype_coercion: Specifies how type coercion should behave. `coerce` (the default) 569 will try to coerce different dtypes in a column to the same one, 570 whereas `strict` will raise an error in case a column contains 571 several dtypes. Note that this only applies to columns whose dtype 572 is guessed, i.e. not specified via `dtypes`. 573 :param use_columns: Specifies the columns to use. Can either be: 574 - `None` to select all columns 575 - A list of strings and ints, the column names and/or indices 576 (starting at 0) 577 - A string, a comma separated list of Excel column letters and column 578 ranges (e.g. `"A:E"` or `"A,C,E:F"`, which would result in 579 `A,B,C,D,E` and `A,C,E,F`). Also supports open-ended ranges 580 (e.g. `"B:"` to select all columns from B onwards) and from-beginning 581 ranges (e.g. `":C"` to select columns from A to C). These can be 582 combined for "except" patterns (e.g. `":C,E:"` to select everything 583 except column D) 584 - A callable, a function that takes a column and returns a boolean 585 indicating whether the column should be used 586 :param dtypes: An optional dtype (for all columns) 587 or dict of dtypes with keys as column indices or names. 588 :param eager: Specifies whether the table should be loaded eagerly. 589 `False` (default) will load the table lazily using the `PyCapsule` interface, 590 whereas `True` will load it eagerly via `pyarrow`. 591 592 Eager loading requires the `pyarrow` extra to be installed. 593 :param skip_whitespace_tail_rows: Skip rows at the end of the table 594 containing only whitespace and null values. 595 :param whitespace_as_null: Consider cells containing only whitespace as null values. 596 :param duplicate_column_separator: Separator between a duplicate column's name and its 597 counter. See "Column naming" in `load_sheet`. 598 :param unnamed_column_prefix: Prefix of generated names for unnamed columns. See 599 "Column naming" in `load_sheet`. 600 """ 601 if eager: 602 return self._reader.load_table( 603 name=name, 604 header_row=header_row, 605 column_names=column_names, 606 skip_rows=skip_rows, 607 n_rows=n_rows, 608 schema_sample_rows=schema_sample_rows, 609 dtype_coercion=dtype_coercion, 610 use_columns=use_columns, 611 dtypes=dtypes, 612 eager=True, 613 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 614 whitespace_as_null=whitespace_as_null, 615 duplicate_column_separator=duplicate_column_separator, 616 unnamed_column_prefix=unnamed_column_prefix, 617 ) 618 else: 619 return ExcelTable( 620 self._reader.load_table( 621 name=name, 622 header_row=header_row, 623 column_names=column_names, 624 skip_rows=skip_rows, 625 n_rows=n_rows, 626 schema_sample_rows=schema_sample_rows, 627 dtype_coercion=dtype_coercion, 628 use_columns=use_columns, 629 dtypes=dtypes, 630 eager=False, 631 skip_whitespace_tail_rows=skip_whitespace_tail_rows, 632 whitespace_as_null=whitespace_as_null, 633 duplicate_column_separator=duplicate_column_separator, 634 unnamed_column_prefix=unnamed_column_prefix, 635 ) 636 )
Loads a table by name.
Parameters
- name: The name of the table to load.
- header_row: The index of the row containing the column labels.
If
None, the table's column names will be used. Any rows before theheader_rowwill be automatically skipped. - column_names: Overrides headers found in the document.
If
column_namesis used,header_rowwill be ignored. - n_rows: Specifies how many rows should be loaded.
If
None, all rows are loaded - skip_rows: Specifies how many rows should be skipped after the
header_row. Any rows before theheader_roware automatically skipped. Ifheader_rowisNone, it skips the number of rows from the start of the sheet. - schema_sample_rows: Specifies how many rows should be used to determine
the dtype of a column. Cannot be 0. A specific dtype can be
enforced for some or all columns through the
dtypesparameter. IfNone, all rows will be used. - dtype_coercion: Specifies how type coercion should behave.
coerce(the default) will try to coerce different dtypes in a column to the same one, whereasstrictwill raise an error in case a column contains several dtypes. Note that this only applies to columns whose dtype is guessed, i.e. not specified viadtypes. - use_columns: Specifies the columns to use. Can either be:
Noneto select all columns- A list of strings and ints, the column names and/or indices (starting at 0)
- A string, a comma separated list of Excel column letters and column
ranges (e.g.
"A:E"or"A,C,E:F", which would result inA,B,C,D,EandA,C,E,F). Also supports open-ended ranges (e.g."B:"to select all columns from B onwards) and from-beginning ranges (e.g.":C"to select columns from A to C). These can be combined for "except" patterns (e.g.":C,E:"to select everything except column D) - A callable, a function that takes a column and returns a boolean indicating whether the column should be used
- dtypes: An optional dtype (for all columns) or dict of dtypes with keys as column indices or names.
eager: Specifies whether the table should be loaded eagerly.
False(default) will load the table lazily using thePyCapsuleinterface, whereasTruewill load it eagerly viapyarrow.Eager loading requires the `pyarrow` extra to be installed.- skip_whitespace_tail_rows: Skip rows at the end of the table containing only whitespace and null values.
- whitespace_as_null: Consider cells containing only whitespace as null values.
- duplicate_column_separator: Separator between a duplicate column's name and its
counter. See "Column naming" in
load_sheet. - unnamed_column_prefix: Prefix of generated names for unnamed columns. See
"Column naming" in
load_sheet.
638 def load_sheet_eager( 639 self, 640 idx_or_name: int | str, 641 *, 642 header_row: int | None = 0, 643 column_names: list[str] | None = None, 644 skip_rows: int | list[int] | Callable[[int], bool] | None = None, 645 n_rows: int | None = None, 646 schema_sample_rows: int | None = 1_000, 647 dtype_coercion: Literal["coerce", "strict"] = "coerce", 648 use_columns: list[str] | list[int] | str | None = None, 649 dtypes: DType | DTypeMap | None = None, 650 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 651 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 652 ) -> pa.RecordBatch: 653 """Loads a sheet eagerly by index or name. 654 655 For xlsx files, this will be faster and more memory-efficient, as it will use 656 `worksheet_range_ref` under the hood, which returns borrowed types. 657 658 Refer to `load_sheet` for parameter documentation 659 660 Requires the `pyarrow` extra to be installed. 661 """ 662 return self._reader.load_sheet( 663 idx_or_name=idx_or_name, 664 header_row=header_row, 665 column_names=column_names, 666 skip_rows=skip_rows, 667 n_rows=n_rows, 668 schema_sample_rows=schema_sample_rows, 669 dtype_coercion=dtype_coercion, 670 use_columns=use_columns, 671 dtypes=dtypes, 672 eager=True, 673 duplicate_column_separator=duplicate_column_separator, 674 unnamed_column_prefix=unnamed_column_prefix, 675 )
Loads a sheet eagerly by index or name.
For xlsx files, this will be faster and more memory-efficient, as it will use
worksheet_range_ref under the hood, which returns borrowed types.
Refer to load_sheet for parameter documentation
Requires the pyarrow extra to be installed.
677 def load_sheet_by_name( 678 self, 679 name: str, 680 *, 681 header_row: int | None = 0, 682 column_names: list[str] | None = None, 683 skip_rows: int | None = None, 684 n_rows: int | None = None, 685 schema_sample_rows: int | None = 1_000, 686 dtype_coercion: Literal["coerce", "strict"] = "coerce", 687 use_columns: list[str] 688 | list[int] 689 | str 690 | Callable[[ColumnInfoNoDtype], bool] 691 | None = None, 692 dtypes: DType | DTypeMap | None = None, 693 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 694 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 695 ) -> ExcelSheet: 696 """Loads a sheet by name. 697 698 Refer to `load_sheet` for parameter documentation 699 """ 700 return self.load_sheet( 701 name, 702 header_row=header_row, 703 column_names=column_names, 704 skip_rows=skip_rows, 705 n_rows=n_rows, 706 schema_sample_rows=schema_sample_rows, 707 dtype_coercion=dtype_coercion, 708 use_columns=use_columns, 709 dtypes=dtypes, 710 duplicate_column_separator=duplicate_column_separator, 711 unnamed_column_prefix=unnamed_column_prefix, 712 )
Loads a sheet by name.
Refer to load_sheet for parameter documentation
714 def load_sheet_by_idx( 715 self, 716 idx: int, 717 *, 718 header_row: int | None = 0, 719 column_names: list[str] | None = None, 720 skip_rows: int | None = None, 721 n_rows: int | None = None, 722 schema_sample_rows: int | None = 1_000, 723 dtype_coercion: Literal["coerce", "strict"] = "coerce", 724 use_columns: list[str] 725 | list[int] 726 | str 727 | Callable[[ColumnInfoNoDtype], bool] 728 | None = None, 729 dtypes: DType | DTypeMap | None = None, 730 duplicate_column_separator: str = DEFAULT_DUPLICATE_COLUMN_SEPARATOR, 731 unnamed_column_prefix: str = DEFAULT_UNNAMED_COLUMN_PREFIX, 732 ) -> ExcelSheet: 733 """Loads a sheet by index. 734 735 Refer to `load_sheet` for parameter documentation 736 """ 737 return self.load_sheet( 738 idx, 739 header_row=header_row, 740 column_names=column_names, 741 skip_rows=skip_rows, 742 n_rows=n_rows, 743 schema_sample_rows=schema_sample_rows, 744 dtype_coercion=dtype_coercion, 745 use_columns=use_columns, 746 dtypes=dtypes, 747 duplicate_column_separator=duplicate_column_separator, 748 unnamed_column_prefix=unnamed_column_prefix, 749 )
Loads a sheet by index.
Refer to load_sheet for parameter documentation
58class ExcelSheet: 59 """A class representing a single sheet in an Excel File""" 60 61 def __init__(self, sheet: _ExcelSheet) -> None: 62 self._sheet = sheet 63 64 @property 65 def name(self) -> str: 66 """The name of the sheet""" 67 return self._sheet.name 68 69 @property 70 def width(self) -> int: 71 """The sheet's width""" 72 return self._sheet.width 73 74 @property 75 def height(self) -> int: 76 """The sheet's height, with `skip_rows` and `nrows` applied""" 77 return self._sheet.height 78 79 @property 80 def total_height(self) -> int: 81 """The sheet's total height""" 82 return self._sheet.total_height 83 84 @property 85 def selected_columns(self) -> list[ColumnInfo]: 86 """The sheet's selected columns""" 87 return self._sheet.selected_columns 88 89 def available_columns(self) -> list[ColumnInfo]: 90 """The columns available for the given sheet""" 91 return self._sheet.available_columns() 92 93 @property 94 def specified_dtypes(self) -> DTypeMap | None: 95 """The dtypes specified for the sheet""" 96 return self._sheet.specified_dtypes 97 98 @property 99 def visible(self) -> SheetVisible: 100 """The visibility of the sheet""" 101 return self._sheet.visible 102 103 def to_arrow(self) -> pa.RecordBatch: 104 """Converts the sheet to a pyarrow `RecordBatch` 105 106 Requires the `pyarrow` extra to be installed. 107 """ 108 if not _PYARROW_AVAILABLE: 109 raise ImportError( 110 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 111 ) 112 return self._sheet.to_arrow() 113 114 def to_arrow_with_errors(self) -> tuple[pa.RecordBatch, CellErrors | None]: 115 """Converts the sheet to a pyarrow `RecordBatch` with error information. 116 117 Stores the positions of any values that cannot be parsed as the specified type and were 118 therefore converted to None. 119 120 Requires the `pyarrow` extra to be installed. 121 """ 122 if not _PYARROW_AVAILABLE: 123 raise ImportError( 124 "pyarrow is required for to_arrow_with_errors(). Install with: pip install 'fastexcel[pyarrow]'" # noqa: E501 125 ) 126 rb, cell_errors = self._sheet.to_arrow_with_errors() 127 if not cell_errors.errors: 128 return (rb, None) 129 return (rb, cell_errors) 130 131 def to_pandas(self) -> pd.DataFrame: 132 """Converts the sheet to a Pandas `DataFrame`. 133 134 Requires the `pandas` extra to be installed. 135 """ 136 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 137 # which we don't implement. Using pyarrow conversion for now. 138 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 139 return self.to_arrow().to_pandas() 140 141 def to_polars(self) -> pl.DataFrame: 142 """Converts the sheet to a Polars `DataFrame`. 143 144 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 145 Requires the `polars` extra to be installed. 146 """ 147 import polars as pl 148 149 return pl.DataFrame(self) 150 151 def __arrow_c_schema__(self) -> object: 152 """Export the schema as an `ArrowSchema` `PyCapsule`. 153 154 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowschema-export 155 156 The Arrow PyCapsule Interface enables zero-copy data exchange with 157 Arrow-compatible libraries without requiring PyArrow as a dependency. 158 """ 159 return self._sheet.__arrow_c_schema__() 160 161 def __arrow_c_array__(self, requested_schema: object | None = None) -> tuple[object, object]: 162 """Export the schema and data as a pair of `ArrowSchema` and `ArrowArray` `PyCapsules`. 163 164 The optional `requested_schema` parameter allows for potential schema conversion. 165 166 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowarray-export 167 168 The Arrow PyCapsule Interface enables zero-copy data exchange with 169 Arrow-compatible libraries without requiring PyArrow as a dependency. 170 """ 171 return self._sheet.__arrow_c_array__(requested_schema) 172 173 def __repr__(self) -> str: 174 return self._sheet.__repr__()
A class representing a single sheet in an Excel File
74 @property 75 def height(self) -> int: 76 """The sheet's height, with `skip_rows` and `nrows` applied""" 77 return self._sheet.height
The sheet's height, with skip_rows and nrows applied
79 @property 80 def total_height(self) -> int: 81 """The sheet's total height""" 82 return self._sheet.total_height
The sheet's total height
84 @property 85 def selected_columns(self) -> list[ColumnInfo]: 86 """The sheet's selected columns""" 87 return self._sheet.selected_columns
The sheet's selected columns
89 def available_columns(self) -> list[ColumnInfo]: 90 """The columns available for the given sheet""" 91 return self._sheet.available_columns()
The columns available for the given sheet
93 @property 94 def specified_dtypes(self) -> DTypeMap | None: 95 """The dtypes specified for the sheet""" 96 return self._sheet.specified_dtypes
The dtypes specified for the sheet
98 @property 99 def visible(self) -> SheetVisible: 100 """The visibility of the sheet""" 101 return self._sheet.visible
The visibility of the sheet
103 def to_arrow(self) -> pa.RecordBatch: 104 """Converts the sheet to a pyarrow `RecordBatch` 105 106 Requires the `pyarrow` extra to be installed. 107 """ 108 if not _PYARROW_AVAILABLE: 109 raise ImportError( 110 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 111 ) 112 return self._sheet.to_arrow()
Converts the sheet to a pyarrow RecordBatch
Requires the pyarrow extra to be installed.
114 def to_arrow_with_errors(self) -> tuple[pa.RecordBatch, CellErrors | None]: 115 """Converts the sheet to a pyarrow `RecordBatch` with error information. 116 117 Stores the positions of any values that cannot be parsed as the specified type and were 118 therefore converted to None. 119 120 Requires the `pyarrow` extra to be installed. 121 """ 122 if not _PYARROW_AVAILABLE: 123 raise ImportError( 124 "pyarrow is required for to_arrow_with_errors(). Install with: pip install 'fastexcel[pyarrow]'" # noqa: E501 125 ) 126 rb, cell_errors = self._sheet.to_arrow_with_errors() 127 if not cell_errors.errors: 128 return (rb, None) 129 return (rb, cell_errors)
Converts the sheet to a pyarrow RecordBatch with error information.
Stores the positions of any values that cannot be parsed as the specified type and were therefore converted to None.
Requires the pyarrow extra to be installed.
131 def to_pandas(self) -> pd.DataFrame: 132 """Converts the sheet to a Pandas `DataFrame`. 133 134 Requires the `pandas` extra to be installed. 135 """ 136 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 137 # which we don't implement. Using pyarrow conversion for now. 138 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 139 return self.to_arrow().to_pandas()
Converts the sheet to a Pandas DataFrame.
Requires the pandas extra to be installed.
141 def to_polars(self) -> pl.DataFrame: 142 """Converts the sheet to a Polars `DataFrame`. 143 144 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 145 Requires the `polars` extra to be installed. 146 """ 147 import polars as pl 148 149 return pl.DataFrame(self)
Converts the sheet to a Polars DataFrame.
Uses the Arrow PyCapsule Interface for zero-copy data exchange.
Requires the polars extra to be installed.
177class ExcelTable: 178 """A class representing a single table in an Excel file""" 179 180 def __init__(self, table: _ExcelTable) -> None: 181 self._table = table 182 183 @property 184 def name(self) -> str: 185 """The name of the table""" 186 return self._table.name 187 188 @property 189 def sheet_name(self) -> str: 190 """The name of the sheet this table belongs to""" 191 return self._table.sheet_name 192 193 @property 194 def width(self) -> int: 195 """The table's width""" 196 return self._table.width 197 198 @property 199 def height(self) -> int: 200 """The table's height""" 201 return self._table.height 202 203 @property 204 def total_height(self) -> int: 205 """The table's total height""" 206 return self._table.total_height 207 208 @property 209 def offset(self) -> int: 210 """The table's offset before data starts""" 211 return self._table.offset 212 213 @property 214 def selected_columns(self) -> list[ColumnInfo]: 215 """The table's selected columns""" 216 return self._table.selected_columns 217 218 def available_columns(self) -> list[ColumnInfo]: 219 """The columns available for the given table""" 220 return self._table.available_columns() 221 222 @property 223 def specified_dtypes(self) -> DTypeMap | None: 224 """The dtypes specified for the table""" 225 return self._table.specified_dtypes 226 227 def to_arrow(self) -> pa.RecordBatch: 228 """Converts the table to a pyarrow `RecordBatch` 229 230 Requires the `pyarrow` extra to be installed. 231 """ 232 if not _PYARROW_AVAILABLE: 233 raise ImportError( 234 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 235 ) 236 return self._table.to_arrow() 237 238 def to_pandas(self) -> pd.DataFrame: 239 """Converts the table to a Pandas `DataFrame`. 240 241 Requires the `pandas` extra to be installed. 242 """ 243 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 244 # which we don't implement. Using pyarrow conversion for now. 245 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 246 return self.to_arrow().to_pandas() 247 248 def to_polars(self) -> pl.DataFrame: 249 """Converts the table to a Polars `DataFrame`. 250 251 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 252 Requires the `polars` extra to be installed. 253 """ 254 import polars as pl 255 256 return pl.DataFrame(self) 257 258 def __arrow_c_schema__(self) -> object: 259 """Export the schema as an `ArrowSchema` `PyCapsule`. 260 261 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowschema-export 262 263 The Arrow PyCapsule Interface enables zero-copy data exchange with 264 Arrow-compatible libraries without requiring PyArrow as a dependency. 265 """ 266 return self._table.__arrow_c_schema__() 267 268 def __arrow_c_array__(self, requested_schema: object | None = None) -> tuple[object, object]: 269 """Export the schema and data as a pair of `ArrowSchema` and `ArrowArray` `PyCapsules`. 270 271 The optional `requested_schema` parameter allows for potential schema conversion. 272 273 https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowarray-export 274 275 The Arrow PyCapsule Interface enables zero-copy data exchange with 276 Arrow-compatible libraries without requiring PyArrow as a dependency. 277 """ 278 return self._table.__arrow_c_array__(requested_schema)
A class representing a single table in an Excel file
183 @property 184 def name(self) -> str: 185 """The name of the table""" 186 return self._table.name
The name of the table
188 @property 189 def sheet_name(self) -> str: 190 """The name of the sheet this table belongs to""" 191 return self._table.sheet_name
The name of the sheet this table belongs to
198 @property 199 def height(self) -> int: 200 """The table's height""" 201 return self._table.height
The table's height
203 @property 204 def total_height(self) -> int: 205 """The table's total height""" 206 return self._table.total_height
The table's total height
208 @property 209 def offset(self) -> int: 210 """The table's offset before data starts""" 211 return self._table.offset
The table's offset before data starts
213 @property 214 def selected_columns(self) -> list[ColumnInfo]: 215 """The table's selected columns""" 216 return self._table.selected_columns
The table's selected columns
218 def available_columns(self) -> list[ColumnInfo]: 219 """The columns available for the given table""" 220 return self._table.available_columns()
The columns available for the given table
222 @property 223 def specified_dtypes(self) -> DTypeMap | None: 224 """The dtypes specified for the table""" 225 return self._table.specified_dtypes
The dtypes specified for the table
227 def to_arrow(self) -> pa.RecordBatch: 228 """Converts the table to a pyarrow `RecordBatch` 229 230 Requires the `pyarrow` extra to be installed. 231 """ 232 if not _PYARROW_AVAILABLE: 233 raise ImportError( 234 "pyarrow is required for to_arrow(). Install with: pip install 'fastexcel[pyarrow]'" 235 ) 236 return self._table.to_arrow()
Converts the table to a pyarrow RecordBatch
Requires the pyarrow extra to be installed.
238 def to_pandas(self) -> pd.DataFrame: 239 """Converts the table to a Pandas `DataFrame`. 240 241 Requires the `pandas` extra to be installed. 242 """ 243 # Note: pandas PyCapsule interface requires __dataframe__ or __arrow_c_stream__ 244 # which we don't implement. Using pyarrow conversion for now. 245 # (see https://pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html) 246 return self.to_arrow().to_pandas()
Converts the table to a Pandas DataFrame.
Requires the pandas extra to be installed.
248 def to_polars(self) -> pl.DataFrame: 249 """Converts the table to a Polars `DataFrame`. 250 251 Uses the Arrow PyCapsule Interface for zero-copy data exchange. 252 Requires the `polars` extra to be installed. 253 """ 254 import polars as pl 255 256 return pl.DataFrame(self)
Converts the table to a Polars DataFrame.
Uses the Arrow PyCapsule Interface for zero-copy data exchange.
Requires the polars extra to be installed.
Metadata about a single column in a sheet.
fastexcel.ColumnNameFrom. How the name of the column was determined.
One of three possible values:
"provided": The column name was provided via theuse_columnsparameter"looked_up": The column name was looked up from the data found in the sheet"generated": The column name was generated from the column index, either becauseheader_rowwasNone, or because it could not be looked up
fastexcel.DTypeFrom. How the dtype of the column was determined.
One of three possible values:
"provided_by_index": The dtype was specified via the column index"provided_by_name": The dtype was specified via the column name"guessed": The dtype was determined from the content of the column
The document properties of a workbook, such as its creator, title and dates.
The base class for all fastexcel errors
Data for a given cell cannot be retrieved
calamine returned an error regarding the content of the cell
Generic calamine error
Sheet was not found
Column was not found
Generic arrow error
Provided parameters are invalid
Column contains an unsupported type combination