From d44e1c423664df0def79aab5f7b6d6834034dbb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torsten=20W=C3=B6rtwein?= Date: Wed, 3 Feb 2021 19:08:20 -0500 Subject: [PATCH] REGR: do not try to infer the excel type from a workbook object --- doc/source/whatsnew/v1.2.2.rst | 1 + pandas/io/excel/_base.py | 2 +- pandas/tests/io/excel/test_openpyxl.py | 24 ++++++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.2.2.rst b/doc/source/whatsnew/v1.2.2.rst index 0ee1abaa2a0eb..9dbb8cdcab237 100644 --- a/doc/source/whatsnew/v1.2.2.rst +++ b/doc/source/whatsnew/v1.2.2.rst @@ -21,6 +21,7 @@ Fixed regressions - Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`) - Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`) - Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`) +- Fixed regression in :func:`read_excel` that caused it to raise a ``ValueError`` when mistakenly treating a workbook object as a file handle (:issue:`39528`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 213be7c05b370..d6aa40a6e17d8 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -1071,7 +1071,7 @@ def __init__( if xlrd_version is not None and isinstance(path_or_buffer, xlrd.Book): ext = "xls" - else: + elif engine in (None, "xlrd") and True: ext = inspect_excel_format( content_or_path=path_or_buffer, storage_options=storage_options ) diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 3155e22d3ff5d..bcad2a88e17a2 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -116,3 +116,27 @@ def test_to_excel_with_openpyxl_engine(ext): ).highlight_max() styled.to_excel(filename, engine="openpyxl") + + +@pytest.mark.parametrize("engine", (None, "openpyxl")) +def test_read_excel_workbook(engine, ext): + # GH 39528 + openpyxl = pytest.importorskip("openpyxl") + expected = tm.makeDataFrame() + message = "Invalid file path or buffer object type" + + with tm.ensure_clean(ext) as filename: + expected.to_excel(filename) + workbook = openpyxl.load_workbook(filename) + if engine is None: + # should raise + try: + with pytest.raises(ValueError, match=message): + df = pd.read_excel(workbook, engine=engine) + finally: + workbook.close() + else: + # should work + df = pd.read_excel(workbook, engine=engine, index_col=0) + workbook.close() + tm.assert_frame_equal(expected, df)