Skip to content

Commit 1f836f1

Browse files
rhshadrachphofl
andauthored
DEPR: Remove deprecated ExcelWriter methods (#50093)
* DEPR: Remove deprecated ExcelWriter methods * Fixup * asv fix * Second asv fix * fixup Co-authored-by: Patrick Hoefler <[email protected]>
1 parent 43bff73 commit 1f836f1

File tree

7 files changed

+12
-178
lines changed

7 files changed

+12
-178
lines changed

asv_bench/benchmarks/io/excel.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,8 @@ def setup(self, engine):
4242
def time_write_excel(self, engine):
4343
bio = BytesIO()
4444
bio.seek(0)
45-
writer = ExcelWriter(bio, engine=engine)
46-
self.df.to_excel(writer, sheet_name="Sheet1")
47-
writer.save()
45+
with ExcelWriter(bio, engine=engine) as writer:
46+
self.df.to_excel(writer, sheet_name="Sheet1")
4847

4948

5049
class WriteExcelStyled:
@@ -57,13 +56,12 @@ def setup(self, engine):
5756
def time_write_excel_style(self, engine):
5857
bio = BytesIO()
5958
bio.seek(0)
60-
writer = ExcelWriter(bio, engine=engine)
61-
df_style = self.df.style
62-
df_style.applymap(lambda x: "border: red 1px solid;")
63-
df_style.applymap(lambda x: "color: blue")
64-
df_style.applymap(lambda x: "border-color: green black", subset=["float1"])
65-
df_style.to_excel(writer, sheet_name="Sheet1")
66-
writer.save()
59+
with ExcelWriter(bio, engine=engine) as writer:
60+
df_style = self.df.style
61+
df_style.applymap(lambda x: "border: red 1px solid;")
62+
df_style.applymap(lambda x: "color: blue")
63+
df_style.applymap(lambda x: "border-color: green black", subset=["float1"])
64+
df_style.to_excel(writer, sheet_name="Sheet1")
6765

6866

6967
class ReadExcel:

doc/source/whatsnew/v2.0.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,8 @@ Removal of prior version deprecations/changes
677677
- Changed default of ``numeric_only`` to ``False`` in :class:`.Resampler` methods (:issue:`47177`)
678678
- Using the method :meth:`DataFrameGroupBy.transform` with a callable that returns DataFrames will align to the input's index (:issue:`47244`)
679679
- When providing a list of columns of length one to :meth:`DataFrame.groupby`, the keys that are returned by iterating over the resulting :class:`DataFrameGroupBy` object will now be tuples of length one (:issue:`47761`)
680+
- Removed deprecated methods :meth:`ExcelWriter.write_cells`, :meth:`ExcelWriter.save`, :meth:`ExcelWriter.cur_sheet`, :meth:`ExcelWriter.handles`, :meth:`ExcelWriter.path` (:issue:`45795`)
681+
- The :class:`ExcelWriter` attribute ``book`` can no longer be set; it is still available to be accessed and mutated (:issue:`48943`)
680682
-
681683

682684
.. ---------------------------------------------------------------------------

pandas/io/excel/_base.py

+1-99
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
cast,
2222
overload,
2323
)
24-
import warnings
2524
import zipfile
2625

2726
from pandas._config import config
@@ -44,7 +43,6 @@
4443
Appender,
4544
doc,
4645
)
47-
from pandas.util._exceptions import find_stack_level
4846

4947
from pandas.core.dtypes.common import (
5048
is_bool,
@@ -1136,40 +1134,6 @@ def book(self):
11361134
This attribute can be used to access engine-specific features.
11371135
"""
11381136

1139-
@book.setter
1140-
@abc.abstractmethod
1141-
def book(self, other) -> None:
1142-
"""
1143-
Set book instance. Class type will depend on the engine used.
1144-
"""
1145-
1146-
def write_cells(
1147-
self,
1148-
cells,
1149-
sheet_name: str | None = None,
1150-
startrow: int = 0,
1151-
startcol: int = 0,
1152-
freeze_panes: tuple[int, int] | None = None,
1153-
) -> None:
1154-
"""
1155-
Write given formatted cells into Excel an excel sheet
1156-
1157-
.. deprecated:: 1.5.0
1158-
1159-
Parameters
1160-
----------
1161-
cells : generator
1162-
cell of formatted data to save to Excel sheet
1163-
sheet_name : str, default None
1164-
Name of Excel sheet, if None, then use self.cur_sheet
1165-
startrow : upper left cell row to dump data frame
1166-
startcol : upper left cell column to dump data frame
1167-
freeze_panes: int tuple of length 2
1168-
contains the bottom-most row and right-most column to freeze
1169-
"""
1170-
self._deprecate("write_cells")
1171-
return self._write_cells(cells, sheet_name, startrow, startcol, freeze_panes)
1172-
11731137
@abc.abstractmethod
11741138
def _write_cells(
11751139
self,
@@ -1194,15 +1158,6 @@ def _write_cells(
11941158
contains the bottom-most row and right-most column to freeze
11951159
"""
11961160

1197-
def save(self) -> None:
1198-
"""
1199-
Save workbook to disk.
1200-
1201-
.. deprecated:: 1.5.0
1202-
"""
1203-
self._deprecate("save")
1204-
return self._save()
1205-
12061161
@abc.abstractmethod
12071162
def _save(self) -> None:
12081163
"""
@@ -1232,7 +1187,7 @@ def __init__(
12321187
# the excel backend first read the existing file and then write any data to it
12331188
mode = mode.replace("a", "r+")
12341189

1235-
# cast ExcelWriter to avoid adding 'if self.handles is not None'
1190+
# cast ExcelWriter to avoid adding 'if self._handles is not None'
12361191
self._handles = IOHandles(
12371192
cast(IO[bytes], path), compression={"compression": None}
12381193
)
@@ -1264,29 +1219,6 @@ def __init__(
12641219
if_sheet_exists = "error"
12651220
self._if_sheet_exists = if_sheet_exists
12661221

1267-
def _deprecate(self, attr: str) -> None:
1268-
"""
1269-
Deprecate attribute or method for ExcelWriter.
1270-
"""
1271-
warnings.warn(
1272-
f"{attr} is not part of the public API, usage can give unexpected "
1273-
"results and will be removed in a future version",
1274-
FutureWarning,
1275-
stacklevel=find_stack_level(),
1276-
)
1277-
1278-
def _deprecate_set_book(self) -> None:
1279-
"""
1280-
Deprecate setting the book attribute - GH#48780.
1281-
"""
1282-
warnings.warn(
1283-
"Setting the `book` attribute is not part of the public API, "
1284-
"usage can give unexpected or corrupted results and will be "
1285-
"removed in a future version",
1286-
FutureWarning,
1287-
stacklevel=find_stack_level(),
1288-
)
1289-
12901222
@property
12911223
def date_format(self) -> str:
12921224
"""
@@ -1308,36 +1240,6 @@ def if_sheet_exists(self) -> str:
13081240
"""
13091241
return self._if_sheet_exists
13101242

1311-
@property
1312-
def cur_sheet(self):
1313-
"""
1314-
Current sheet for writing.
1315-
1316-
.. deprecated:: 1.5.0
1317-
"""
1318-
self._deprecate("cur_sheet")
1319-
return self._cur_sheet
1320-
1321-
@property
1322-
def handles(self) -> IOHandles[bytes]:
1323-
"""
1324-
Handles to Excel sheets.
1325-
1326-
.. deprecated:: 1.5.0
1327-
"""
1328-
self._deprecate("handles")
1329-
return self._handles
1330-
1331-
@property
1332-
def path(self):
1333-
"""
1334-
Path to Excel file.
1335-
1336-
.. deprecated:: 1.5.0
1337-
"""
1338-
self._deprecate("path")
1339-
return self._path
1340-
13411243
def __fspath__(self) -> str:
13421244
return getattr(self._handles.handle, "name", "")
13431245

pandas/io/excel/_odswriter.py

-10
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
)
2525

2626
if TYPE_CHECKING:
27-
from odf.opendocument import OpenDocumentSpreadsheet
28-
2927
from pandas.io.formats.excel import ExcelCell
3028

3129

@@ -72,14 +70,6 @@ def book(self):
7270
"""
7371
return self._book
7472

75-
@book.setter
76-
def book(self, other: OpenDocumentSpreadsheet) -> None:
77-
"""
78-
Set book instance. Class type will depend on the engine used.
79-
"""
80-
self._deprecate_set_book()
81-
self._book = other
82-
8373
@property
8474
def sheets(self) -> dict[str, Any]:
8575
"""Mapping of sheet names to sheet objects."""

pandas/io/excel/_openpyxl.py

-8
Original file line numberDiff line numberDiff line change
@@ -88,14 +88,6 @@ def book(self) -> Workbook:
8888
"""
8989
return self._book
9090

91-
@book.setter
92-
def book(self, other: Workbook) -> None:
93-
"""
94-
Set book instance. Class type will depend on the engine used.
95-
"""
96-
self._deprecate_set_book()
97-
self._book = other
98-
9991
@property
10092
def sheets(self) -> dict[str, Any]:
10193
"""Mapping of sheet names to sheet objects."""

pandas/io/excel/_xlsxwriter.py

+1-15
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
from __future__ import annotations
22

3-
from typing import (
4-
TYPE_CHECKING,
5-
Any,
6-
)
3+
from typing import Any
74

85
from pandas._libs import json
96
from pandas._typing import (
@@ -18,9 +15,6 @@
1815
validate_freeze_panes,
1916
)
2017

21-
if TYPE_CHECKING:
22-
from xlsxwriter import Workbook
23-
2418

2519
class _XlsxStyler:
2620
# Map from openpyxl-oriented styles to flatter xlsxwriter representation
@@ -224,14 +218,6 @@ def book(self):
224218
"""
225219
return self._book
226220

227-
@book.setter
228-
def book(self, other: Workbook) -> None:
229-
"""
230-
Set book instance. Class type will depend on the engine used.
231-
"""
232-
self._deprecate_set_book()
233-
self._book = other
234-
235221
@property
236222
def sheets(self) -> dict[str, Any]:
237223
result = self.book.sheetnames

pandas/tests/io/excel/test_writers.py

-36
Original file line numberDiff line numberDiff line change
@@ -1234,42 +1234,6 @@ def test_to_excel_empty_frame(self, engine, ext):
12341234
expected = DataFrame()
12351235
tm.assert_frame_equal(result, expected)
12361236

1237-
@pytest.mark.parametrize("attr", ["cur_sheet", "handles", "path"])
1238-
def test_deprecated_attr(self, engine, ext, attr):
1239-
# GH#45572
1240-
with tm.ensure_clean(ext) as path:
1241-
with ExcelWriter(path) as writer:
1242-
msg = f"{attr} is not part of the public API"
1243-
with tm.assert_produces_warning(FutureWarning, match=msg):
1244-
getattr(writer, attr)
1245-
# Some engines raise if nothing is written
1246-
DataFrame().to_excel(writer)
1247-
1248-
@pytest.mark.filterwarnings("ignore:Calling close():UserWarning:xlsxwriter")
1249-
@pytest.mark.parametrize(
1250-
"attr, args", [("save", ()), ("write_cells", ([], "test"))]
1251-
)
1252-
def test_deprecated_method(self, engine, ext, attr, args):
1253-
# GH#45572
1254-
with tm.ensure_clean(ext) as path:
1255-
with ExcelWriter(path) as writer:
1256-
msg = f"{attr} is not part of the public API"
1257-
# Some engines raise if nothing is written
1258-
DataFrame().to_excel(writer)
1259-
with tm.assert_produces_warning(FutureWarning, match=msg):
1260-
getattr(writer, attr)(*args)
1261-
1262-
def test_deprecated_book_setter(self, engine, ext):
1263-
# GH#48780
1264-
with tm.ensure_clean(ext) as path:
1265-
with ExcelWriter(path) as writer:
1266-
msg = "Setting the `book` attribute is not part of the public API"
1267-
# Some engines raise if nothing is written
1268-
DataFrame().to_excel(writer)
1269-
book = writer.book
1270-
with tm.assert_produces_warning(FutureWarning, match=msg):
1271-
writer.book = book
1272-
12731237

12741238
class TestExcelWriterEngineTests:
12751239
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)