Skip to content

BUG: read_excel with openpyxl produces trailing rows of nan #39547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Feb 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
2bcf35b
BUG: read_excel with openpyxl and missing dimension
rhshadrach Jan 30, 2021
ea18d61
fixups
rhshadrach Jan 30, 2021
d5215f7
Added fixes for incorrect dimension information
rhshadrach Jan 31, 2021
d6c3af1
Return "" for null date columns, trim empty trailing rows
rhshadrach Jan 31, 2021
c51340c
whatsnew
rhshadrach Jan 31, 2021
8cd7aad
Removed fix for 39181
rhshadrach Feb 1, 2021
7ed5c36
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 1, 2021
b70b65d
BUG: read_excel with openpyxl produces trailing rows of nan
rhshadrach Feb 1, 2021
ea150b3
Add test excel file
rhshadrach Feb 1, 2021
b887183
REG: read_excel with engine specified raises on non-path/non-buffer
rhshadrach Feb 3, 2021
2291988
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 3, 2021
601ad87
Restore special-casing for xlrd.Book even when engine is None
rhshadrach Feb 3, 2021
d835dff
GH # in test
rhshadrach Feb 3, 2021
e6684e9
Added wb.close() to test
rhshadrach Feb 4, 2021
1f16602
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 5, 2021
ba2bc75
Added logic/tests for determining if a sheet is read-only
rhshadrach Feb 5, 2021
1381ecc
Added comment
rhshadrach Feb 5, 2021
a3db3eb
Combine and reorg tests
rhshadrach Feb 5, 2021
becd2cf
-
rhshadrach Feb 5, 2021
41e8b81
Merge branch 'openpyxl_workbook' of https://github.com/rhshadrach/pan…
rhshadrach Feb 5, 2021
d773418
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 7, 2021
a3b6369
Added xlsx test file
rhshadrach Feb 7, 2021
e9f6fa2
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 7, 2021
3e9bd4f
xfail and improve tests
rhshadrach Feb 8, 2021
b5d662b
Merge branch 'master' of https://github.com/pandas-dev/pandas into op…
rhshadrach Feb 8, 2021
8773c32
Merge branch 'master' into openpyxl_nans
simonjayhawkins Feb 8, 2021
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Bug fixes

- :func:`pandas.read_excel` error message when a specified ``sheetname`` does not exist is now uniform across engines (:issue:`39250`)
- Fixed bug in :func:`pandas.read_excel` producing incorrect results when the engine ``openpyxl`` is used and the excel file is missing or has incorrect dimension information; the fix requires ``openpyxl`` >= 3.0.0, prior versions may still fail (:issue:`38956`, :issue:`39001`)
- Fixed bug in :func:`pandas.read_excel` sometimes producing a ``DataFrame`` with trailing rows of ``np.nan`` when the engine ``openpyxl`` is used (:issue:`39181`)

.. ---------------------------------------------------------------------------

Expand Down
6 changes: 6 additions & 0 deletions pandas/io/excel/_openpyxl.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,10 +546,16 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
sheet.reset_dimensions()

data: List[List[Scalar]] = []
last_row_with_data = -1
for row_number, row in enumerate(sheet.rows):
converted_row = [self._convert_cell(cell, convert_float) for cell in row]
if not all(cell == "" for cell in converted_row):
last_row_with_data = row_number
data.append(converted_row)

# Trim trailing empty rows
data = data[: last_row_with_data + 1]

if version >= "3.0.0" and is_readonly and len(data) > 0:
# With dimension reset, openpyxl no longer pads rows
max_width = max(len(data_row) for data_row in data)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With some xlsx files I get an error:

max() arg is an empty sequence

I am pretty sure this happens when data object is empty

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't share the file but I can tell it starts with empty rows and empty columns.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep - thanks for catching this!

Expand Down
Binary file not shown.
Binary file not shown.
40 changes: 40 additions & 0 deletions pandas/tests/io/excel/test_openpyxl.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,43 @@ def test_append_mode_file(ext):
second = data.find(b"docProps/app.xml", first + 1)
third = data.find(b"docProps/app.xml", second + 1)
assert second != -1 and third == -1


# When read_only is None, use read_excel instead of a workbook
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_with_empty_trailing_rows(datapath, ext, read_only, request):
# GH 39181
version = LooseVersion(get_version(openpyxl))
if (read_only or read_only is None) and version < "3.0.0":
msg = "openpyxl read-only sheet is incorrect when dimension data is wrong"
request.node.add_marker(pytest.mark.xfail(reason=msg))
path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}")
if read_only is None:
result = pd.read_excel(path)
else:
wb = openpyxl.load_workbook(path, read_only=read_only)
result = pd.read_excel(wb, engine="openpyxl")
wb.close()
expected = DataFrame(
{
"Title": [np.nan, "A", 1, 2, 3],
"Unnamed: 1": [np.nan, "B", 4, 5, 6],
"Unnamed: 2": [np.nan, "C", 7, 8, 9],
}
)
tm.assert_frame_equal(result, expected)


# When read_only is None, use read_excel instead of a workbook
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_empty_with_blank_row(datapath, ext, read_only):
# GH 39547 - empty excel file with a row that has no data
path = datapath("io", "data", "excel", f"empty_with_blank_row{ext}")
if read_only is None:
result = pd.read_excel(path)
else:
wb = openpyxl.load_workbook(path, read_only=read_only)
result = pd.read_excel(wb, engine="openpyxl")
wb.close()
expected = DataFrame()
tm.assert_frame_equal(result, expected)