Skip to content

Backport PR #48660 on branch 1.5.x (Fix Excel-specific border styles) #50204

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 2 commits into from
Dec 12, 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
3 changes: 2 additions & 1 deletion doc/source/user_guide/style.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1594,8 +1594,9 @@
"\n",
"\n",
"- Only CSS2 named colors and hex colors of the form `#rgb` or `#rrggbb` are currently supported.\n",
"- The following pseudo CSS properties are also available to set excel specific style properties:\n",
"- The following pseudo CSS properties are also available to set Excel specific style properties:\n",
" - `number-format`\n",
" - `border-style` (for Excel-specific styles: \"hair\", \"mediumDashDot\", \"dashDotDot\", \"mediumDashDotDot\", \"dashDot\", \"slantDashDot\", or \"mediumDashed\")\n",
"\n",
"Table level styles, and data cell CSS-classes are not included in the export to Excel: individual cells must have their properties mapped by the `Styler.apply` and/or `Styler.applymap` methods."
]
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Fixed regressions

Bug fixes
~~~~~~~~~
- Bug in :meth:`.Styler.to_excel` leading to error when unrecognized ``border-style`` (e.g. ``"hair"``) provided to Excel writers (:issue:`48649`)
- Bug when chaining several :meth:`.Styler.concat` calls, only the last styler was concatenated (:issue:`49207`)
-

Expand Down
11 changes: 9 additions & 2 deletions pandas/io/formats/css.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,9 @@ def expand(self, prop, value: str) -> Generator[tuple[str, str], None, None]:
f"border{side}-width": "medium",
}
for token in tokens:
if token in self.BORDER_STYLES:
if token.lower() in self.BORDER_STYLES:
border_declarations[f"border{side}-style"] = token
elif any([ratio in token for ratio in self.BORDER_WIDTH_RATIOS]):
elif any(ratio in token.lower() for ratio in self.BORDER_WIDTH_RATIOS):
border_declarations[f"border{side}-width"] = token
else:
border_declarations[f"border{side}-color"] = token
Expand Down Expand Up @@ -181,6 +181,13 @@ class CSSResolver:
"ridge",
"inset",
"outset",
"mediumdashdot",
"dashdotdot",
"hair",
"mediumdashdotdot",
"dashdot",
"slantdashdot",
"mediumdashed",
]

SIDE_SHORTHANDS = {
Expand Down
26 changes: 26 additions & 0 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,22 @@ class CSSToExcelConverter:
"fantasy": 5, # decorative
}

BORDER_STYLE_MAP = {
style.lower(): style
for style in [
"dashed",
"mediumDashDot",
"dashDotDot",
"hair",
"dotted",
"mediumDashDotDot",
"double",
"dashDot",
"slantDashDot",
"mediumDashed",
]
}

# NB: Most of the methods here could be classmethods, as only __init__
# and __call__ make use of instance attributes. We leave them as
# instancemethods so that users can easily experiment with extensions
Expand Down Expand Up @@ -306,6 +322,16 @@ def _border_style(self, style: str | None, width: str | None, color: str | None)
if width_name in ("hair", "thin"):
return "dashed"
return "mediumDashed"
elif style in self.BORDER_STYLE_MAP:
# Excel-specific styles
return self.BORDER_STYLE_MAP[style]
else:
warnings.warn(
f"Unhandled border style format: {repr(style)}",
CSSWarning,
stacklevel=find_stack_level(),
)
return "none"

def _get_width_name(self, width_input: str | None) -> str | None:
width = self._width_to_float(width_input)
Expand Down
62 changes: 62 additions & 0 deletions pandas/tests/io/excel/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ def test_styler_to_excel_unstyled(engine):
["border", "left", "color", "rgb"],
{"xlsxwriter": "FF111222", "openpyxl": "00111222"},
),
# Border styles
(
"border-left-style: hair; border-left-color: black",
["border", "left", "style"],
"hair",
),
]


Expand Down Expand Up @@ -196,6 +202,62 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected):
assert sc_cell == expected


# From https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.borders.html
# Note: Leaving behavior of "width"-type styles undefined; user should use border-width
# instead
excel_border_styles = [
# "thin",
"dashed",
"mediumDashDot",
"dashDotDot",
"hair",
"dotted",
"mediumDashDotDot",
# "medium",
"double",
"dashDot",
"slantDashDot",
# "thick",
"mediumDashed",
]


@pytest.mark.parametrize(
"engine",
["xlsxwriter", "openpyxl"],
)
@pytest.mark.parametrize("border_style", excel_border_styles)
def test_styler_to_excel_border_style(engine, border_style):
css = f"border-left: {border_style} black thin"
attrs = ["border", "left", "style"]
expected = border_style

pytest.importorskip(engine)
df = DataFrame(np.random.randn(1, 1))
styler = df.style.applymap(lambda x: css)

with tm.ensure_clean(".xlsx") as path:
with ExcelWriter(path, engine=engine) as writer:
df.to_excel(writer, sheet_name="dataframe")
styler.to_excel(writer, sheet_name="styled")

openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl
with contextlib.closing(openpyxl.load_workbook(path)) as wb:

# test unstyled data cell does not have expected styles
# test styled cell has expected styles
u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2)
for attr in attrs:
u_cell, s_cell = getattr(u_cell, attr, None), getattr(s_cell, attr)

if isinstance(expected, dict):
assert u_cell is None or u_cell != expected[engine]
assert s_cell == expected[engine]
else:
assert u_cell is None or u_cell != expected
assert s_cell == expected


def test_styler_custom_converter():
openpyxl = pytest.importorskip("openpyxl")

Expand Down