Skip to content

Commit 0bd52be

Browse files
authored
ENH: Add sheet name to error message when reading Excel (#49186)
1 parent dbe0c10 commit 0bd52be

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

doc/source/whatsnew/v2.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ MultiIndex
344344
I/O
345345
^^^
346346
- Bug in :func:`read_sas` caused fragmentation of :class:`DataFrame` and raised :class:`.errors.PerformanceWarning` (:issue:`48595`)
347+
- Improved error message in :func:`read_excel` by including the offending sheet name when an exception is raised while reading a file (:issue:`48706`)
347348
- Bug when a pickling a subset PyArrow-backed data that would serialize the entire data instead of the subset (:issue:`42600`)
348349
- Bug in :func:`read_csv` for a single-line csv with fewer columns than ``names`` raised :class:`.errors.ParserError` with ``engine="c"`` (:issue:`47566`)
349350
-

pandas/io/excel/_base.py

+4
Original file line numberDiff line numberDiff line change
@@ -863,6 +863,10 @@ def parse(
863863
# No Data, return an empty DataFrame
864864
output[asheetname] = DataFrame()
865865

866+
except Exception as err:
867+
err.args = (f"{err.args[0]} (sheet: {asheetname})", *err.args[1:])
868+
raise err
869+
866870
if ret_dict:
867871
return output
868872
else:

pandas/tests/io/excel/test_readers.py

+7
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,13 @@ def test_read_excel_blank_with_header(self, read_ext):
624624
actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1")
625625
tm.assert_frame_equal(actual, expected)
626626

627+
def test_exception_message_includes_sheet_name(self, read_ext):
628+
# GH 48706
629+
with pytest.raises(ValueError, match=r" \(sheet: Sheet1\)$"):
630+
pd.read_excel("blank_with_header" + read_ext, header=[1], sheet_name=None)
631+
with pytest.raises(ZeroDivisionError, match=r" \(sheet: Sheet1\)$"):
632+
pd.read_excel("test1" + read_ext, usecols=lambda x: 1 / 0, sheet_name=None)
633+
627634
@pytest.mark.filterwarnings("ignore:Cell A4 is marked:UserWarning:openpyxl")
628635
def test_date_conversion_overflow(self, request, engine, read_ext):
629636
# GH 10001 : pandas.ExcelFile ignore parse_dates=False

0 commit comments

Comments
 (0)