Skip to content

DOC+BUG: Styler.to_excel pseudo css number-format #46239

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 6 commits into from
Mar 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added doc/source/_static/style/format_excel_css.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.drop` and :meth:`Series.drop` when :class:`Index` had extension dtype and duplicates (:issue:`45860`)
- Fixed memory performance regression in :meth:`Series.fillna` when called on a :class:`DataFrame` column with ``inplace=True`` (:issue:`46149`)
- Provided an alternative solution for passing custom Excel formats in :meth:`.Styler.to_excel`, which was a regression based on stricter CSS validation. Examples available in the documentation for :meth:`.Styler.format` (:issue:`46152`)
-

.. ---------------------------------------------------------------------------
Expand Down
4 changes: 3 additions & 1 deletion pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,9 @@ def build_fill(self, props: Mapping[str, str]):
return {"fgColor": self.color_to_excel(fill_color), "patternType": "solid"}

def build_number_format(self, props: Mapping[str, str]) -> dict[str, str | None]:
return {"format_code": props.get("number-format")}
fc = props.get("number-format")
fc = fc.replace("§", ";") if isinstance(fc, str) else fc
return {"format_code": fc}

def build_font(
self, props: Mapping[str, str]
Expand Down
34 changes: 34 additions & 0 deletions pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,6 +992,10 @@ def format(
-------
self : Styler

See Also
--------
Styler.format_index: Format the text display value of index labels.

Notes
-----
This method assigns a formatting function, ``formatter``, to each cell in the
Expand Down Expand Up @@ -1027,6 +1031,12 @@ def format(
- ``styler.format.thousands``: default None.
- ``styler.format.escape``: default None.

.. warning::
`Styler.format` is ignored when using the output format `Styler.to_excel`,
since Excel and Python have inherrently different formatting structures.
However, it is possible to use the `number-format` pseudo CSS attribute
to force Excel permissible formatting. See examples.

Examples
--------
Using ``na_rep`` and ``precision`` with the default ``formatter``
Expand Down Expand Up @@ -1094,6 +1104,19 @@ def format(
1 & \textbf{\textasciitilde \space \textasciicircum } \\
2 & \textbf{\$\%\#} \\
\end{tabular}

Pandas defines a `number-format` pseudo CSS attribute instead of the `.format`
method to create `to_excel` permissible formatting. Note that semi-colons are
CSS protected characters but used as separators in Excel's format string.
Replace semi-colons with the section separator character (ASCII-245) when
defining the formatting here.

>>> df = pd.DataFrame({"A": [1, 0, -1]})
>>> pseudo_css = "number-format: 0§[Red](0)§-§@;"
>>> df.style.applymap(lambda v: css).to_excel("formatted_file.xlsx")
... # doctest: +SKIP

.. figure:: ../../_static/style/format_excel_css.png
"""
if all(
(
Expand Down Expand Up @@ -1185,6 +1208,10 @@ def format_index(
-------
self : Styler

See Also
--------
Styler.format: Format the text display value of data cells.

Notes
-----
This method assigns a formatting function, ``formatter``, to each level label
Expand All @@ -1211,6 +1238,13 @@ def format_index(
When using a ``formatter`` string the dtypes must be compatible, otherwise a
`ValueError` will be raised.

.. warning::
`Styler.format_index` is ignored when using the output format
`Styler.to_excel`, since Excel and Python have inherrently different
formatting structures.
However, it is possible to use the `number-format` pseudo CSS attribute
to force Excel permissible formatting. See documentation for `Styler.format`.

Examples
--------
Using ``na_rep`` and ``precision`` with the default ``formatter``
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/io/formats/test_to_excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@
("white-space: normal", {"alignment": {"wrap_text": True}}),
# NUMBER FORMAT
("number-format: 0%", {"number_format": {"format_code": "0%"}}),
(
"number-format: 0§[Red](0)§-§@;",
{"number_format": {"format_code": "0;[red](0);-;@"}}, # GH 46152
),
],
)
def test_css_to_excel(css, expected):
Expand Down