diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 844e062b20ca3..7c7112bae0ff3 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -665,6 +665,7 @@ I/O - Bug in :func:`read_json` where date strings with ``Z`` were not converted to a UTC timezone (:issue:`26168`) - Added ``cache_dates=True`` parameter to :meth:`read_csv`, which allows to cache unique dates when they are parsed (:issue:`25990`) - :meth:`DataFrame.to_excel` now raises a ``ValueError`` when the caller's dimensions exceed the limitations of Excel (:issue:`26051`) +- :func:`read_excel` now raises a ``ValueError`` when input is of type :class:`pandas.io.excel.ExcelFile` and ``engine`` param is passed since :class:`pandas.io.excel.ExcelFile` has an engine defined (:issue:`26566`) Plotting ^^^^^^^^ diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 24412b26b021b..631461b3d14ab 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -289,6 +289,9 @@ def read_excel(io, if not isinstance(io, ExcelFile): io = ExcelFile(io, engine=engine) + elif engine and engine != io.engine: + raise ValueError("Engine should not be specified when passing " + "an ExcelFile - ExcelFile already has the engine set") return io.parse( sheet_name=sheet_name, @@ -777,6 +780,7 @@ def __init__(self, io, engine=None): if engine not in self._engines: raise ValueError("Unknown engine: {engine}".format(engine=engine)) + self.engine = engine # could be a str, ExcelFile, Book, etc. self.io = io # Always a string diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 140727599b182..48fb6b705a4a4 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -834,3 +834,14 @@ def test_reader_closes_file(self, read_ext): pd.read_excel(xlsx, 'Sheet1', index_col=0) assert f.closed + + @pytest.mark.parametrize('excel_engine', [ + 'xlrd', + None + ]) + def test_read_excel_engine_value(self, read_ext, excel_engine): + # GH 26566 + xl = ExcelFile("test1" + read_ext, engine=excel_engine) + msg = "Engine should not be specified when passing an ExcelFile" + with pytest.raises(ValueError, match=msg): + pd.read_excel(xl, engine='openpyxl')