Skip to content

Fix Excel-specific border styles #48660

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 32 commits into from
Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e3f2ea8
Add tests
tehunter Sep 20, 2022
1657735
Add support for "hair" style
tehunter Sep 20, 2022
16258a9
Support excel-specific border styles
tehunter Sep 20, 2022
6626a97
Use black border if styled but color unspecified
tehunter Sep 20, 2022
69d75fa
Added documentation and whatsnew
tehunter Sep 20, 2022
25ad970
Black linter
tehunter Sep 20, 2022
e7d7eb0
Merge branch 'main' into excel-border-hair
tehunter Sep 20, 2022
d2680ef
Fixed tests for Excel border color fallback
tehunter Sep 20, 2022
ec3e137
Revert style.ipynb metadata
tehunter Sep 22, 2022
fb0f81c
Fix typo
tehunter Sep 22, 2022
cb8068a
Revert border-color default value
tehunter Sep 26, 2022
d169d3a
Revert "Fixed tests for Excel border color fallback"
tehunter Sep 26, 2022
e632719
Revert border color default tests
tehunter Sep 27, 2022
222cf3a
Updated whatsnew entry
tehunter Sep 27, 2022
f7b698c
Merge branch 'main' into excel-border-hair
tehunter Sep 27, 2022
3e65ce7
Add method link to whatsnew
tehunter Sep 28, 2022
db09655
Merge branch 'main' into excel-border-hair
tehunter Sep 28, 2022
e352a1c
Add tests and fix case sensitivity
tehunter Sep 28, 2022
c6e4c5c
Merge branch 'main' into excel-border-hair
tehunter Sep 28, 2022
d9fad6d
Apply black linter
tehunter Sep 28, 2022
7c9f7d0
Merge remote-tracking branch 'upstream/main' into excel-border-hair
tehunter Nov 2, 2022
a6abe18
Update v1.5.2.rst
tehunter Nov 2, 2022
eae63aa
Merge remote-tracking branch 'upstream/main' into excel-border-hair
tehunter Nov 10, 2022
e050967
Merge remote-tracking branch 'upstream/main' into excel-border-hair
tehunter Nov 10, 2022
0ae7634
Fix documentation typo
tehunter Nov 10, 2022
69366ae
Test that border shorthand works
tehunter Nov 10, 2022
ba774f7
Append Excel styles to shorthand parsing
tehunter Nov 10, 2022
97fd1c1
Update to find_stack_level call
tehunter Nov 10, 2022
84273e3
Merge remote-tracking branch 'upstream/main' into excel-border-hair
tehunter Nov 11, 2022
b5773f5
Merge branch 'main' into excel-border-hair
tehunter Nov 14, 2022
8a0f656
Merge remote-tracking branch 'upstream/main' into excel-border-hair
tehunter Nov 23, 2022
b6f6212
Update v1.5.3.rst
tehunter Nov 23, 2022
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,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`)
-

.. ---------------------------------------------------------------------------
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