Skip to content

Commit dfba035

Browse files
committed
TST: narrow PR to tests-only; revert engine and unrelated test changes
1 parent ea941f6 commit dfba035

File tree

9 files changed

+123
-167
lines changed

9 files changed

+123
-167
lines changed

pandas/core/generic.py

Lines changed: 98 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,8 @@
189189
from pandas.io.formats.printing import pprint_thing
190190

191191
if TYPE_CHECKING:
192+
from collections.abc import Callable
192193
from collections.abc import (
193-
Callable,
194194
Hashable,
195195
Iterator,
196196
Mapping,
@@ -2180,128 +2180,139 @@ def to_excel(
21802180
freeze_panes: tuple[int, int] | None = None,
21812181
storage_options: StorageOptions | None = None,
21822182
engine_kwargs: dict[str, Any] | None = None,
2183-
autofilter: bool = False,
21842183
) -> None:
21852184
"""
2186-
Write object to an Excel sheet.
2185+
Write {klass} to an Excel sheet.
21872186
2188-
To write a single object to an Excel .xlsx file it is only necessary
2189-
to specify a target file name.
2187+
To write a single {klass} to an Excel .xlsx file it is only necessary to
2188+
specify a target file name. To write to multiple sheets it is necessary to
2189+
create an `ExcelWriter` object with a target file name, and specify a sheet
2190+
in the file to write to.
21902191
2191-
.. code-block:: python
2192-
2193-
df.to_excel("path_to_file.xlsx")
2194-
2195-
To write to different sheets of the same .xlsx file it is necessary to
2196-
create an `ExcelWriter` object with a target file name,
2197-
and specify a sheet in the file to write to.
2198-
2199-
.. code-block:: python
2200-
2201-
with pd.ExcelWriter("path_to_file.xlsx") as writer:
2202-
df1.to_excel(writer, sheet_name="Sheet_name_1")
2203-
df2.to_excel(writer, sheet_name="Sheet_name_2")
2204-
2205-
When using `ExcelWriter`, note that the objects are not written until the
2206-
`ExcelWriter` object is closed.
2192+
Multiple sheets may be written to by specifying unique `sheet_name`.
2193+
With all data written to the file it is necessary to save the changes.
2194+
Note that creating an `ExcelWriter` object with a file name that already
2195+
exists will result in the contents of the existing file being erased.
22072196
22082197
Parameters
22092198
----------
2210-
excel_writer : string, path object or ExcelWriter object
2211-
File path or existing ExcelWriter
2212-
If a string is passed, a new ExcelWriter object is created.
2199+
excel_writer : path-like, file-like, or ExcelWriter object
2200+
File path or existing ExcelWriter.
22132201
sheet_name : str, default 'Sheet1'
22142202
Name of sheet which will contain DataFrame.
22152203
na_rep : str, default ''
2216-
Missing data representation
2217-
float_format : str, default None
2218-
Format string for floating point numbers
2219-
columns : sequence, optional
2220-
Columns to write
2204+
Missing data representation.
2205+
float_format : str, optional
2206+
Format string for floating point numbers. For example
2207+
``float_format="%.2f"`` will format 0.1234 to 0.12.
2208+
columns : sequence or list of str, optional
2209+
Columns to write.
22212210
header : bool or list of str, default True
2222-
Write out the column names. If a list of string is given
2223-
it is assumed to be aliases for the column names
2211+
Write out the column names. If a list of string is given it is
2212+
assumed to be aliases for the column names.
22242213
index : bool, default True
2225-
Write row names (index)
2226-
index_label : str or sequence, default None
2227-
Column label for index column(s) if desired. If None is given, and
2214+
Write row names (index).
2215+
index_label : str or sequence, optional
2216+
Column label for index column(s) if desired. If not specified, and
22282217
`header` and `index` are True, then the index names are used. A
22292218
sequence should be given if the DataFrame uses MultiIndex.
22302219
startrow : int, default 0
22312220
Upper left cell row to dump data frame.
2232-
Per default (0) header is written, too.
22332221
startcol : int, default 0
22342222
Upper left cell column to dump data frame.
22352223
engine : str, optional
2236-
Write engine to use, 'openpyxl' or 'xlsxwriter'.
2237-
Defaults to 'xlsxwriter'.
2238-
merge_cells : bool, default True
2239-
Write MultiIndex and Hierarchical Rows as merged cells.
2240-
The indices corresponding to each row will be combined and
2241-
presented as a single cell.
2224+
Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this
2225+
via the options ``io.excel.xlsx.writer`` or
2226+
``io.excel.xlsm.writer``.
2227+
2228+
merge_cells : bool or 'columns', default False
2229+
If True, write MultiIndex index and columns as merged cells.
2230+
If 'columns', merge MultiIndex column cells only.
2231+
{encoding_parameter}
22422232
inf_rep : str, default 'inf'
2243-
Representation for infinity (there is no native Numpy representation
2244-
for infinity in integer dtypes)
2245-
freeze_panes : tuple of int (length 2), default None
2246-
First rows to freeze panes on. Only applicable when `freeze_panes`
2247-
is passed as a tuple.
2248-
storage_options : dict, optional
2249-
Extra options that make sense for a particular storage connection,
2250-
e.g. host, port, username, password, etc., if using a URL that
2251-
requires authentication.
2252-
engine_kwargs : dict, optional
2253-
Arbitrary keyword arguments passed to excel engine.
2254-
autofilter : bool, default False
2255-
Whether to apply autofilter to the header row.
2233+
Representation for infinity (there is no native representation for
2234+
infinity in Excel).
2235+
{verbose_parameter}
2236+
freeze_panes : tuple of int (length 2), optional
2237+
Specifies the one-based bottommost row and rightmost column that
2238+
is to be frozen.
2239+
{storage_options}
22562240
2241+
.. versionadded:: {storage_options_versionadded}
2242+
{extra_parameters}
22572243
See Also
22582244
--------
2259-
read_excel : Read from an Excel file into a DataFrame.
2260-
ExcelFile : Class for parsing tabular excel files.
2245+
to_csv : Write DataFrame to a comma-separated values (csv) file.
22612246
ExcelWriter : Class for writing DataFrame objects into excel sheets.
2247+
read_excel : Read an Excel file into a pandas DataFrame.
2248+
read_csv : Read a comma-separated values (csv) file into DataFrame.
2249+
io.formats.style.Styler.to_excel : Add styles to Excel sheet.
22622250
22632251
Notes
22642252
-----
2265-
The `engine` keyword is not supported when `excel_writer` is an
2266-
existing `ExcelWriter`.
2253+
For compatibility with :meth:`~DataFrame.to_csv`,
2254+
to_excel serializes lists and dicts to strings before writing.
2255+
2256+
Once a workbook has been saved it is not possible to write further
2257+
data without rewriting the whole workbook.
2258+
2259+
pandas will check the number of rows, columns,
2260+
and cell character count does not exceed Excel's limitations.
2261+
All other limitations must be checked by the user.
22672262
22682263
Examples
22692264
--------
2270-
>>> df = pd.DataFrame({{"A": [1, 2, 3], "B": [4, 5, 6]}})
2271-
>>> df.to_excel("pandas_simple.xlsx")
2272-
>>> df.to_excel("pandas_simple.xlsx", engine="openpyxl")
2265+
2266+
Create, write to and save a workbook:
2267+
2268+
>>> df1 = pd.DataFrame(
2269+
... [["a", "b"], ["c", "d"]],
2270+
... index=["row 1", "row 2"],
2271+
... columns=["col 1", "col 2"],
2272+
... )
2273+
>>> df1.to_excel("output.xlsx") # doctest: +SKIP
2274+
2275+
To specify the sheet name:
2276+
2277+
>>> df1.to_excel("output.xlsx", sheet_name="Sheet_name_1") # doctest: +SKIP
2278+
2279+
If you wish to write to more than one sheet in the workbook, it is
2280+
necessary to specify an ExcelWriter object:
2281+
2282+
>>> df2 = df1.copy()
2283+
>>> with pd.ExcelWriter("output.xlsx") as writer: # doctest: +SKIP
2284+
... df1.to_excel(writer, sheet_name="Sheet_name_1")
2285+
... df2.to_excel(writer, sheet_name="Sheet_name_2")
2286+
2287+
ExcelWriter can also be used to append to an existing Excel file:
2288+
2289+
>>> with pd.ExcelWriter("output.xlsx", mode="a") as writer: # doctest: +SKIP
2290+
... df1.to_excel(writer, sheet_name="Sheet_name_3")
2291+
2292+
To set the library that is used to write the Excel file,
2293+
you can pass the `engine` keyword (the default engine is
2294+
automatically chosen depending on the file extension):
2295+
2296+
>>> df1.to_excel("output1.xlsx", engine="xlsxwriter") # doctest: +SKIP
22732297
"""
2274-
# Import ExcelWriter here to avoid circular import
2275-
from pandas import ExcelWriter
2298+
if engine_kwargs is None:
2299+
engine_kwargs = {}
22762300

2277-
if isinstance(excel_writer, ExcelWriter):
2278-
if engine is not None:
2279-
raise ValueError(
2280-
"engine should not be specified when passing an ExcelWriter"
2281-
)
2282-
engine = excel_writer.engine
2283-
else:
2284-
excel_writer = ExcelWriter(
2285-
excel_writer,
2286-
engine=engine,
2287-
engine_kwargs=engine_kwargs,
2288-
storage_options=storage_options,
2289-
)
2301+
df = self if isinstance(self, ABCDataFrame) else self.to_frame()
22902302

2291-
# Import ExcelFormatter here to avoid circular import
22922303
from pandas.io.formats.excel import ExcelFormatter
22932304

22942305
formatter = ExcelFormatter(
2295-
self,
2306+
df,
22962307
na_rep=na_rep,
2297-
float_format=float_format,
2298-
columns=columns,
2308+
cols=columns,
22992309
header=header,
2310+
float_format=float_format,
23002311
index=index,
23012312
index_label=index_label,
2313+
merge_cells=merge_cells,
23022314
inf_rep=inf_rep,
23032315
)
2304-
23052316
formatter.write(
23062317
excel_writer,
23072318
sheet_name=sheet_name,
@@ -2311,13 +2322,8 @@ def to_excel(
23112322
engine=engine,
23122323
storage_options=storage_options,
23132324
engine_kwargs=engine_kwargs,
2314-
autofilter=autofilter,
23152325
)
23162326

2317-
if not isinstance(excel_writer, ExcelWriter):
2318-
# we need to close the writer if we created it
2319-
excel_writer.close()
2320-
23212327
@final
23222328
@doc(
23232329
storage_options=_shared_docs["storage_options"],
@@ -4845,6 +4851,7 @@ def sort_values(
48454851
ignore_index: bool = ...,
48464852
key: ValueKeyFunc = ...,
48474853
) -> Self: ...
4854+
48484855
@overload
48494856
def sort_values(
48504857
self,
@@ -9607,10 +9614,10 @@ def align(
96079614
1 1 2 3 4
96089615
2 6 7 8 9
96099616
>>> other
9610-
A B C D E
9611-
2 10 20 30 40 NaN
9612-
3 60 70 80 90 NaN
9613-
4 600 700 800 900 NaN
9617+
A B C D
9618+
2 10 20 30 40
9619+
3 60 70 80 90
9620+
4 600 700 800 900
96149621
96159622
Align on columns:
96169623
@@ -12037,6 +12044,7 @@ def last_valid_index(self) -> Hashable:
1203712044
{see_also}\
1203812045
{examples}
1203912046
"""
12047+
1204012048
_sum_prod_doc = """
1204112049
{desc}
1204212050

pandas/io/excel/_base.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,6 @@ def _write_cells(
12091209
startrow: int = 0,
12101210
startcol: int = 0,
12111211
freeze_panes: tuple[int, int] | None = None,
1212-
autofilter: bool = False,
12131212
) -> None:
12141213
"""
12151214
Write given formatted cells into Excel an excel sheet
@@ -1224,8 +1223,6 @@ def _write_cells(
12241223
startcol : upper left cell column to dump data frame
12251224
freeze_panes: int tuple of length 2
12261225
contains the bottom-most row and right-most column to freeze
1227-
autofilter : bool, default False
1228-
If True, apply an autofilter to the header row over the written data range.
12291226
"""
12301227
raise NotImplementedError
12311228

pandas/io/excel/_odswriter.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,10 @@ def _write_cells(
9999
startrow: int = 0,
100100
startcol: int = 0,
101101
freeze_panes: tuple[int, int] | None = None,
102-
autofilter: bool = False,
103102
) -> None:
104103
"""
105104
Write the frame cells using odf
106105
"""
107-
if autofilter:
108-
raise NotImplementedError(
109-
"Autofilter is not supported with the 'odf' engine. "
110-
"Please use 'openpyxl' or 'xlsxwriter' engine instead."
111-
)
112-
113106
from odf.table import (
114107
Table,
115108
TableCell,

pandas/io/excel/_openpyxl.py

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,6 @@ def _write_cells(
449449
startrow: int = 0,
450450
startcol: int = 0,
451451
freeze_panes: tuple[int, int] | None = None,
452-
autofilter: bool = False,
453452
) -> None:
454453
# Write the frame cells using openpyxl.
455454
sheet_name = self._get_sheet_name(sheet_name)
@@ -487,11 +486,6 @@ def _write_cells(
487486
row=freeze_panes[0] + 1, column=freeze_panes[1] + 1
488487
)
489488

490-
min_r = None
491-
min_c = None
492-
max_r = None
493-
max_c = None
494-
495489
for cell in cells:
496490
xcell = wks.cell(
497491
row=startrow + cell.row + 1, column=startcol + cell.col + 1
@@ -512,23 +506,10 @@ def _write_cells(
512506
for k, v in style_kwargs.items():
513507
setattr(xcell, k, v)
514508

515-
abs_row = startrow + cell.row + 1
516-
abs_col = startcol + cell.col + 1
517-
518-
# track bounds (1-based for openpyxl)
519-
if min_r is None or abs_row < min_r:
520-
min_r = abs_row
521-
if min_c is None or abs_col < min_c:
522-
min_c = abs_col
523-
if max_r is None or abs_row > max_r:
524-
max_r = abs_row
525-
if max_c is None or abs_col > max_c:
526-
max_c = abs_col
527-
528509
if cell.mergestart is not None and cell.mergeend is not None:
529510
wks.merge_cells(
530-
start_row=abs_row,
531-
start_column=abs_col,
511+
start_row=startrow + cell.row + 1,
512+
start_column=startcol + cell.col + 1,
532513
end_column=startcol + cell.mergeend + 1,
533514
end_row=startrow + cell.mergestart + 1,
534515
)
@@ -551,14 +532,6 @@ def _write_cells(
551532
for k, v in style_kwargs.items():
552533
setattr(xcell, k, v)
553534

554-
if autofilter and min_r is not None and min_c is not None and max_r is not None and max_c is not None:
555-
# Convert numeric bounds to Excel-style range e.g. A1:D10
556-
from openpyxl.utils import get_column_letter
557-
558-
start_ref = f"{get_column_letter(min_c)}{min_r}"
559-
end_ref = f"{get_column_letter(max_c)}{max_r}"
560-
wks.auto_filter.ref = f"{start_ref}:{end_ref}"
561-
562535

563536
class OpenpyxlReader(BaseExcelReader["Workbook"]):
564537
@doc(storage_options=_shared_docs["storage_options"])

0 commit comments

Comments
 (0)