Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
83 changes: 48 additions & 35 deletions python/python_calamine/_python_calamine.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
Expand Down Expand Up @@ -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,
Expand Down
36 changes: 28 additions & 8 deletions src/types/sheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ impl From<SheetVisible> for SheetVisibleEnum {

type MergedCellRange = ((u32, u32), (u32, u32));

fn cell_value(value: &Data, empty_as_none: bool) -> Option<CellValue> {
if empty_as_none && matches!(value, Data::Empty) {
None
} else {
Some(value.into())
}
}

#[pyclass(from_py_object)]
#[derive(Clone, PartialEq)]
pub struct SheetMetadata {
Expand Down Expand Up @@ -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<u32>,
empty_as_none: bool,
) -> PyResult<Bound<'_, PyList>> {
let nrows = match nrows {
Some(nrows) => nrows,
Expand All @@ -212,16 +221,20 @@ 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<CellValue>>::into))?;
let py_row = PyList::new(
slf.py(),
row.iter().map(|cell| cell_value(cell, empty_as_none)),
)?;

py_list.append(py_row)?;
}

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]
Expand All @@ -236,19 +249,21 @@ impl CalamineSheet {
pub struct CalamineCellIterator {
position: u32,
start: (u32, u32),
empty_row: Vec<CellValue>,
empty_row: Vec<Option<CellValue>>,
empty_as_none: bool,
iter: Rows<'static, Data>,
#[allow(dead_code)]
range: Arc<Range<Data>>,
}

impl CalamineCellIterator {
fn from_range(range: Arc<Range<Data>>) -> CalamineCellIterator {
fn from_range(range: Arc<Range<Data>>, 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 {
Expand Down Expand Up @@ -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<CellValue>>::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()
Expand Down
Binary file added tests/data/empty-string.xls
Binary file not shown.
Binary file added tests/data/empty-string.xlsx
Binary file not shown.
30 changes: 30 additions & 0 deletions tests/test_empty_cells.py
Original file line number Diff line number Diff line change
@@ -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
Loading