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
Merged

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

merged 9 commits into from
Feb 15, 2024

Conversation

rmhowe425
Copy link
Contributor

@rmhowe425 rmhowe425 commented Jul 29, 2023

@rmhowe425
Copy link
Contributor Author

@rhshadrach pinging on green

@@ -176,6 +176,7 @@ Other enhancements
- Performance improvement in :func:`concat` with homogeneous ``np.float64`` or ``np.float32`` dtypes (:issue:`52685`)
- Performance improvement in :meth:`DataFrame.filter` when ``items`` is given (:issue:`52941`)
- Reductions :meth:`Series.argmax`, :meth:`Series.argmin`, :meth:`Series.idxmax`, :meth:`Series.idxmin`, :meth:`Index.argmax`, :meth:`Index.argmin`, :meth:`DataFrame.idxmax`, :meth:`DataFrame.idxmin` are now supported for object-dtype objects (:issue:`4279`, :issue:`18021`, :issue:`40685`, :issue:`43697`)
- 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.

From the issue, this change will need to happen in 3.0 not 2.1

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@mroeschke Looks like there is no whatsnew file yet for 3.0.

I can just create one by creating a template based on 2.1?

Copy link
Member

Choose a reason for hiding this comment

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

We'll create one once we release 2.2 (in December), so let's hold on with this PR for now

@mroeschke mroeschke added the Styler conditional formatting using DataFrame.style label Jul 31, 2023

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 ``Styler.to_excel``
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 use :meth:`Styler.to_excel` and also add a reference to the section in the User Guide: https://pandas.pydata.org/docs/user_guide/style.html#Export-to-Excel

Comment on lines 3937 to 3938
css = "border: 1pt solid #111222"
styler = df.style.map(lambda x: css)
Copy link
Member

Choose a reason for hiding this comment

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

I don't think this is equivalent to how Excel files are currently styled, is that right? Would it make sense to do that instead?

Copy link
Contributor

@attack68 attack68 Aug 3, 2023

Choose a reason for hiding this comment

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

I agree, think we need to provide the exact replication. Typing on phone now but I suggest the its probably going to be something like;

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

It might need text-align as well - I cant remember off hand.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@attack68 Yeah doing a quick comparison of the above with a basic call to DataFrame.to_excel() shows that the above styling is the same as the current default styling.

@mroeschke mroeschke added this to the 3.0 milestone Aug 8, 2023
@github-actions
Copy link
Contributor

github-actions bot commented Sep 8, 2023

This pull request is stale because it has been open for thirty days with no activity. Please update and respond to this comment if you're still interested in working on this.

@github-actions github-actions bot added the Stale label Sep 8, 2023
@rmhowe425
Copy link
Contributor Author

This pull request is stale because it has been open for thirty days with no activity. Please update and respond to this comment if you're still interested in working on this.

Still interested in working on this PR. Waiting for whatsnew v3.0 to come out

@mroeschke
Copy link
Member

@rmhowe425 the 3.0.0.rst whatsnew is out now. Are you still interested in continuing this?

@rmhowe425
Copy link
Contributor Author

@rmhowe425 the 3.0.0.rst whatsnew is out now. Are you still interested in continuing this?

Yes I am still interested! Thank you for pinging me and letting me know!

Comment on lines 148 to 180
@pytest.mark.parametrize(
"css",
["background-color: #111222"],
)
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

@mroeschke mroeschke removed the Stale label Feb 6, 2024
@rmhowe425
Copy link
Contributor Author

@rhshadrach @mroeschke Pinging on green.

Did you guys want me to combine my unit tests into one test as recommended here?

IMHO I think it makes more sense to keep them separated, but happy to combine them if you guys want me to.

Copy link
Contributor

@attack68 attack68 left a comment

Choose a reason for hiding this comment

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

I think separate tests is fine. LGTM and passes tests.

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

@@ -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?

@rmhowe425 rmhowe425 requested a review from mroeschke February 15, 2024 21:00
@rmhowe425
Copy link
Contributor Author

@mroeschke Pinging on green

Copy link
Member

@rhshadrach rhshadrach left a comment

Choose a reason for hiding this comment

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

Nice tests, lgtm.

@mroeschke mroeschke merged commit db54438 into pandas-dev:main Feb 15, 2024
@mroeschke
Copy link
Member

Thanks @rmhowe425

@rmhowe425 rmhowe425 deleted the dev/to_excel/format branch February 17, 2024 17:19
pmhatre1 pushed a commit to pmhatre1/pandas-pmhatre1 that referenced this pull request May 7, 2024
…as-dev#54302)

* Updated default styling logic for to_excel and added unit tests.

* Adding documentation to the Pandas User Guide.

* Updating whatsnew

* Fixing merge conflict.

* Updating user guide documentation.

* Fixing syntax error.

* Updating implementation based on reviewer feedback.

* Updating documentation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Styler conditional formatting using DataFrame.style
Projects
None yet
Development

Successfully merging this pull request may close these issues.

REF: Proposal: change DataFrame.to_excel to output unformatted excel file
5 participants