Skip to content

ENH: Change DataFrame.to_excel to output unformatted excel file #54302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 15, 2024
14 changes: 14 additions & 0 deletions doc/source/user_guide/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3908,6 +3908,20 @@ The look and feel of Excel worksheets created from pandas can be modified using
* ``float_format`` : Format string for floating point numbers (default ``None``).
* ``freeze_panes`` : A tuple of two integers representing the bottommost row and rightmost column to freeze. Each of these parameters is one-based, so (1, 1) will freeze the first row and first column (default ``None``).

.. note::

As of Pandas 3.0, by default spreadsheets created with the ``to_excel`` method
will not contain any styling. Users wishing to bold text, add bordered styles,
etc in a worksheet output by ``to_excel`` can do so by using :meth:`Styler.to_excel`
to create styled excel files. For documentation on styling spreadsheets, see
`here <https://pandas.pydata.org/docs/user_guide/style.html#Export-to-Excel>`__.


.. code-block:: python

css = "border: 1px solid black; font-weight: bold;"
df.style.map_index(lambda x: css).map_index(lambda x: css, axis=1).to_excel("myfile.xlsx")

Using the `Xlsxwriter`_ engine provides many options for controlling the
format of an Excel worksheet created with the ``to_excel`` method. Excellent examples can be found in the
`Xlsxwriter`_ documentation here: https://xlsxwriter.readthedocs.io/working_with_pandas.html
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Other enhancements
- :func:`read_stata` now returns ``datetime64`` resolutions better matching those natively stored in the stata format (:issue:`55642`)
- Allow dictionaries to be passed to :meth:`pandas.Series.str.replace` via ``pat`` parameter (:issue:`51748`)
- Support passing a :class:`Series` input to :func:`json_normalize` that retains the :class:`Series` :class:`Index` (:issue:`51452`)
-
- Updated :meth:`DataFrame.to_excel` so that the output spreadsheet has no styling. (:issue:`54154`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you put this under Other API Changes and also mention that styling can still be done with Styler.to_excel?


.. ---------------------------------------------------------------------------
.. _whatsnew_300.notable_bug_fixes:
Expand Down
33 changes: 10 additions & 23 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,19 +582,6 @@ def __init__(
self.merge_cells = merge_cells
self.inf_rep = inf_rep

@property
def header_style(self) -> dict[str, dict[str, str | bool]]:
return {
"font": {"bold": True},
"borders": {
"top": "thin",
"right": "thin",
"bottom": "thin",
"left": "thin",
},
"alignment": {"horizontal": "center", "vertical": "top"},
}

def _format_value(self, val):
if is_scalar(val) and missing.isna(val):
val = self.na_rep
Expand Down Expand Up @@ -642,7 +629,7 @@ def _format_header_mi(self) -> Iterable[ExcelCell]:
row=lnum,
col=coloffset,
val=name,
style=self.header_style,
style=None,
)

for lnum, (spans, levels, level_codes) in enumerate(
Expand All @@ -657,7 +644,7 @@ def _format_header_mi(self) -> Iterable[ExcelCell]:
row=lnum,
col=coloffset + i + 1,
val=values[i],
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_columns", None),
css_row=lnum,
css_col=i,
Expand All @@ -673,7 +660,7 @@ def _format_header_mi(self) -> Iterable[ExcelCell]:
row=lnum,
col=coloffset + i + 1,
val=v,
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_columns", None),
css_row=lnum,
css_col=i,
Expand Down Expand Up @@ -706,7 +693,7 @@ def _format_header_regular(self) -> Iterable[ExcelCell]:
row=self.rowcounter,
col=colindex + coloffset,
val=colname,
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_columns", None),
css_row=0,
css_col=colindex,
Expand All @@ -729,7 +716,7 @@ def _format_header(self) -> Iterable[ExcelCell]:
] * len(self.columns)
if functools.reduce(lambda x, y: x and y, (x != "" for x in row)):
gen2 = (
ExcelCell(self.rowcounter, colindex, val, self.header_style)
ExcelCell(self.rowcounter, colindex, val, None)
for colindex, val in enumerate(row)
)
self.rowcounter += 1
Expand Down Expand Up @@ -763,7 +750,7 @@ def _format_regular_rows(self) -> Iterable[ExcelCell]:
self.rowcounter += 1

if index_label and self.header is not False:
yield ExcelCell(self.rowcounter - 1, 0, index_label, self.header_style)
yield ExcelCell(self.rowcounter - 1, 0, index_label, None)

# write index_values
index_values = self.df.index
Expand All @@ -775,7 +762,7 @@ def _format_regular_rows(self) -> Iterable[ExcelCell]:
row=self.rowcounter + idx,
col=0,
val=idxval,
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_index", None),
css_row=idx,
css_col=0,
Expand Down Expand Up @@ -811,7 +798,7 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
# if index labels are not empty go ahead and dump
if com.any_not_none(*index_labels) and self.header is not False:
for cidx, name in enumerate(index_labels):
yield ExcelCell(self.rowcounter - 1, cidx, name, self.header_style)
yield ExcelCell(self.rowcounter - 1, cidx, name, None)

if self.merge_cells:
# Format hierarchical rows as merged cells.
Expand All @@ -838,7 +825,7 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
row=self.rowcounter + i,
col=gcolidx,
val=values[i],
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_index", None),
css_row=i,
css_col=gcolidx,
Expand All @@ -856,7 +843,7 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]:
row=self.rowcounter + idx,
col=gcolidx,
val=indexcolval,
style=self.header_style,
style=None,
css_styles=getattr(self.styler, "ctx_index", None),
css_row=idx,
css_col=gcolidx,
Expand Down
55 changes: 55 additions & 0 deletions pandas/tests/io/excel/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,28 @@ def assert_equal_cell_styles(cell1, cell2):
assert cell1.protection.__dict__ == cell2.protection.__dict__


def test_styler_default_values():
# GH 54154
openpyxl = pytest.importorskip("openpyxl")
df = DataFrame([{"A": 1, "B": 2, "C": 3}, {"A": 1, "B": 2, "C": 3}])

with tm.ensure_clean(".xlsx") as path:
with ExcelWriter(path, engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="custom")

with contextlib.closing(openpyxl.load_workbook(path)) as wb:
# Check font, spacing, indentation
assert wb["custom"].cell(1, 1).font.bold is False
assert wb["custom"].cell(1, 1).alignment.horizontal is None
assert wb["custom"].cell(1, 1).alignment.vertical is None

# Check border
assert wb["custom"].cell(1, 1).border.bottom.color is None
assert wb["custom"].cell(1, 1).border.top.color is None
assert wb["custom"].cell(1, 1).border.left.color is None
assert wb["custom"].cell(1, 1).border.right.color is None


@pytest.mark.parametrize(
"engine",
["xlsxwriter", "openpyxl"],
Expand Down Expand Up @@ -123,6 +145,39 @@ def test_styler_to_excel_unstyled(engine):
]


@pytest.mark.parametrize(
"css",
["background-color: #111222"],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you inline this in the test since it's only 1 parameter

)
def test_styler_custom_style(css):
# GH 54154
openpyxl = pytest.importorskip("openpyxl")
df = DataFrame([{"A": 1, "B": 2}, {"A": 1, "B": 2}])

with tm.ensure_clean(".xlsx") as path:
with ExcelWriter(path, engine="openpyxl") as writer:
styler = df.style.map(lambda x: css)
styler.to_excel(writer, sheet_name="custom", index=False)

with contextlib.closing(openpyxl.load_workbook(path)) as wb:
# Check font, spacing, indentation
assert wb["custom"].cell(1, 1).font.bold is False
assert wb["custom"].cell(1, 1).alignment.horizontal is None
assert wb["custom"].cell(1, 1).alignment.vertical is None

# Check border
assert wb["custom"].cell(1, 1).border.bottom.color is None
assert wb["custom"].cell(1, 1).border.top.color is None
assert wb["custom"].cell(1, 1).border.left.color is None
assert wb["custom"].cell(1, 1).border.right.color is None

# Check background color
assert wb["custom"].cell(2, 1).fill.fgColor.index == "00111222"
assert wb["custom"].cell(3, 1).fill.fgColor.index == "00111222"
assert wb["custom"].cell(2, 2).fill.fgColor.index == "00111222"
assert wb["custom"].cell(3, 2).fill.fgColor.index == "00111222"


Copy link
Contributor

@weikhor weikhor Feb 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can simplify code test by combining both functions test_styler_default_values and test_styler_custom_style to one function.

@pytest.mark.parametrize(
    "css, color",
    [("", "00000000"), 
     ("background-color: #111222", "00111222")],
)
def test_default_and_custom_style(css, color):
    # GH 54154
    openpyxl = pytest.importorskip("openpyxl")
    df = DataFrame([{"A": 1, "B": 2}, {"A": 1, "B": 2}])

    with tm.ensure_clean(".xlsx") as path:
        with ExcelWriter(path, engine="openpyxl") as writer:
            styler = df.style.map(lambda x: css)
            styler.to_excel(writer, sheet_name="custom", index=False)

        with contextlib.closing(openpyxl.load_workbook(path)) as wb:
            # Check font, spacing, indentation
            assert wb["custom"].cell(1, 1).font.bold is False
            assert wb["custom"].cell(1, 1).alignment.horizontal is None
            assert wb["custom"].cell(1, 1).alignment.vertical is None

            # Check border
            assert wb["custom"].cell(1, 1).border.bottom.color is None
            assert wb["custom"].cell(1, 1).border.top.color is None
            assert wb["custom"].cell(1, 1).border.left.color is None
            assert wb["custom"].cell(1, 1).border.right.color is None

            # Check background color
            assert wb["custom"].cell(2, 1).fill.fgColor.index == color
            assert wb["custom"].cell(3, 1).fill.fgColor.index == color
            assert wb["custom"].cell(2, 2).fill.fgColor.index == color
            assert wb["custom"].cell(3, 2).fill.fgColor.index == color

@pytest.mark.parametrize(
"engine",
["xlsxwriter", "openpyxl"],
Expand Down