diff --git a/README.md b/README.md index c8c0e0b..debdd7d 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,19 @@ workbook = CalamineWorkbook.from_path("file.xlsx").get_sheet_by_name("Sheet1").t # ] ``` +By default, empty cells are returned as `""`. Set `empty_as_none=True` on +`to_python()` or `iter_rows()` to return `None` for empty cells instead; actual +empty strings remain `""` when the underlying format preserves them. This also +applies to leading empty rows or columns included in the result. Error values +retain their existing conversion. + +```python +sheet = CalamineWorkbook.from_path("file.xlsx").get_sheet_by_name("Sheet1") +rows = sheet.to_python(empty_as_none=True) +for row in sheet.iter_rows(empty_as_none=True): + print(row) +``` + Workbook document properties, such as the author, are available for xlsx, xlsb, xls and ods files. ```python from python_calamine import CalamineWorkbook diff --git a/python/python_calamine/_python_calamine.pyi b/python/python_calamine/_python_calamine.pyi index 4273b54..8972ad1 100644 --- a/python/python_calamine/_python_calamine.pyi +++ b/python/python_calamine/_python_calamine.pyi @@ -7,6 +7,17 @@ import os import types import typing +_CellValue = ( + int + | float + | str + | bool + | datetime.time + | datetime.date + | datetime.datetime + | datetime.timedelta +) + @typing.type_check_only class ReadBuffer(typing.Protocol): def seek(self, __offset: int, __whence: int = ...) -> int: ... @@ -74,44 +85,46 @@ class CalamineSheet: def end(self) -> tuple[int, int] | None: """Get bottom right cell position of a sheet data.""" + @typing.overload def to_python( - self, skip_empty_area: bool = True, nrows: int | None = None - ) -> list[ - list[ - int - | float - | str - | bool - | datetime.time - | datetime.date - | datetime.datetime - | datetime.timedelta - ] - ]: - """Returning data from sheet as list of lists. - - Args: - skip_empty_area (bool): - By default, calamine skips empty rows/cols before data. - For suppress this behaviour, set `skip_empty_area` to `False`. - """ - - def iter_rows( self, - ) -> typing.Iterator[ - list[ - int - | float - | str - | bool - | datetime.time - | datetime.date - | datetime.datetime - | datetime.timedelta - ] - ]: - """Returning data from sheet as iterator of lists.""" + skip_empty_area: bool = True, + nrows: int | None = None, + *, + empty_as_none: typing.Literal[False] = False, + ) -> list[list[_CellValue]]: + """Return sheet rows, optionally including leading empty rows and columns.""" + + @typing.overload + def to_python( + self, + skip_empty_area: bool = True, + nrows: int | None = None, + *, + empty_as_none: typing.Literal[True], + ) -> list[list[_CellValue | None]]: ... + @typing.overload + def to_python( + self, + skip_empty_area: bool = True, + nrows: int | None = None, + *, + empty_as_none: bool, + ) -> list[list[_CellValue | None]]: ... + @typing.overload + def iter_rows( + self, *, empty_as_none: typing.Literal[False] = False + ) -> typing.Iterator[list[_CellValue]]: + """Return an iterator over sheet rows.""" + @typing.overload + def iter_rows( + self, *, empty_as_none: typing.Literal[True] + ) -> typing.Iterator[list[_CellValue | None]]: ... + @typing.overload + def iter_rows( + self, *, empty_as_none: bool + ) -> typing.Iterator[list[_CellValue | None]]: ... @property def merged_cell_ranges( self, diff --git a/src/types/sheet.rs b/src/types/sheet.rs index c696c80..3d5c69c 100644 --- a/src/types/sheet.rs +++ b/src/types/sheet.rs @@ -70,6 +70,14 @@ impl From for SheetVisibleEnum { type MergedCellRange = ((u32, u32), (u32, u32)); +fn cell_value(value: &Data, empty_as_none: bool) -> Option { + if empty_as_none && matches!(value, Data::Empty) { + None + } else { + Some(value.into()) + } +} + #[pyclass(from_py_object)] #[derive(Clone, PartialEq)] pub struct SheetMetadata { @@ -187,11 +195,12 @@ impl CalamineSheet { self.range.end() } - #[pyo3(signature = (skip_empty_area=true, nrows=None))] + #[pyo3(signature = (skip_empty_area=true, nrows=None, *, empty_as_none=false))] fn to_python( slf: PyRef<'_, Self>, skip_empty_area: bool, nrows: Option, + empty_as_none: bool, ) -> PyResult> { let nrows = match nrows { Some(nrows) => nrows, @@ -212,7 +221,10 @@ impl CalamineSheet { let py_list = PyList::empty(slf.py()); for row in range.rows().take(nrows as usize) { - let py_row = PyList::new(slf.py(), row.iter().map(<&Data as Into>::into))?; + let py_row = PyList::new( + slf.py(), + row.iter().map(|cell| cell_value(cell, empty_as_none)), + )?; py_list.append(py_row)?; } @@ -220,8 +232,9 @@ impl CalamineSheet { Ok(py_list) } - fn iter_rows(&self) -> CalamineCellIterator { - CalamineCellIterator::from_range(Arc::clone(&self.range)) + #[pyo3(signature = (*, empty_as_none=false))] + fn iter_rows(&self, empty_as_none: bool) -> CalamineCellIterator { + CalamineCellIterator::from_range(Arc::clone(&self.range), empty_as_none) } #[getter] @@ -236,19 +249,21 @@ impl CalamineSheet { pub struct CalamineCellIterator { position: u32, start: (u32, u32), - empty_row: Vec, + empty_row: Vec>, + empty_as_none: bool, iter: Rows<'static, Data>, #[allow(dead_code)] range: Arc>, } impl CalamineCellIterator { - fn from_range(range: Arc>) -> CalamineCellIterator { + fn from_range(range: Arc>, empty_as_none: bool) -> CalamineCellIterator { let empty_row = (0..range.width()) - .map(|_| CellValue::String("".to_string())) + .map(|_| cell_value(&Data::Empty, empty_as_none)) .collect(); CalamineCellIterator { empty_row, + empty_as_none, position: 0, start: range.start().unwrap_or_default(), iter: unsafe { @@ -277,7 +292,12 @@ impl CalamineCellIterator { if slf.position > slf.start.0 { slf.iter .next() - .map(|row| PyList::new(slf.py(), row.iter().map(<&Data as Into>::into))) + .map(|row| { + PyList::new( + slf.py(), + row.iter().map(|cell| cell_value(cell, slf.empty_as_none)), + ) + }) .transpose() } else { Some(PyList::new(slf.py(), slf.empty_row.clone())).transpose() diff --git a/tests/data/empty-string.xls b/tests/data/empty-string.xls new file mode 100644 index 0000000..0845d64 Binary files /dev/null and b/tests/data/empty-string.xls differ diff --git a/tests/data/empty-string.xlsx b/tests/data/empty-string.xlsx new file mode 100644 index 0000000..f3ba843 Binary files /dev/null and b/tests/data/empty-string.xlsx differ diff --git a/tests/test_empty_cells.py b/tests/test_empty_cells.py new file mode 100644 index 0000000..804d514 --- /dev/null +++ b/tests/test_empty_cells.py @@ -0,0 +1,30 @@ +from pathlib import Path + +import pytest +from python_calamine import CalamineWorkbook + +DATA = Path(__file__).parent / "data" + + +@pytest.mark.parametrize("filename", ["empty-string.xls", "empty-string.xlsx"]) +def test_empty_cell_and_empty_formula_result(filename): + sheet = CalamineWorkbook.from_path(DATA / filename).get_sheet_by_index(0) + expected = [["", "x"], [None, "x"]] + default = [["", "x"], ["", "x"]] + if filename.endswith(".xlsx"): + # Error cells still use the legacy conversion, regardless of the option. + expected = [["", "x", ""], [None, "x", None]] + default = [["", "x", ""], ["", "x", ""]] + + assert sheet.to_python() == default + assert list(sheet.iter_rows()) == default + assert sheet.to_python(empty_as_none=True) == expected + assert list(sheet.iter_rows(empty_as_none=True)) == expected + + +def test_leading_empty_rows_and_columns(): + sheet = CalamineWorkbook.from_path(DATA / "base.xlsx").get_sheet_by_index(0) + assert sheet.to_python(skip_empty_area=False, nrows=1, empty_as_none=True) == [ + [None] * 10 + ] + assert next(sheet.iter_rows(empty_as_none=True)) == [None] * 10