13

I'm using openpyxl 2.0.3 with python2.7.

Is there a way to apply a style to every cell in a worksheet? Lets say I want to change the font of all cells, similar to how I would open an excel document, hit ctrl+a, right click and change the format.

2 Answers 2

6

Updated: The comments show DEFAULT_FONT class can now be imported and the properties set directly before saving workbook:

from openpyxl.workbook import Workbook
from openpyxl.styles import DEFAULT_FONT
wb = Workbook()
wb.active['B3'] = "Hello"
DEFAULT_FONT.name = "Arial"
wb.save("DemoDefaultFont.xlsx")

More is needed to set multiple properties simultaneously. Copy the properties from a temporary Font object:

from openpyxl.workbook import Workbook
from openpyxl.styles import DEFAULT_FONT
from openpyxl.styles import Font
wb = Workbook()
wb.active['B3'] = "Hello"
_font = Font(name="Arial", sz=10, b=True)
{k: setattr(DEFAULT_FONT, k, v) for k, v in _font.__dict__.items()}
wb.save("DemoDefaultFont.xlsx")

Further details: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/fonts.html?highlight=default_font

4
  • How about importing DEFAULT_FONT and alter it with something like DEFAULT_FONT.name = "Arial"? I just did it, it works (openpyxl 3.0.7, Python 3.6). Jul 7, 2021 at 7:54
  • 3
    The above import didn't work for me on OpenPyXL 3.0.7, Python 3.9.7. I've had success using from openpyxl.styles import DEFAULT_FONT. Afterword, changing values was a cinch. E.g. DEFAULT_FONT.size = 11
    – FrankieD
    Sep 7, 2021 at 23:26
  • Updated answer to change DEFAULT_FONT, hack no longer required
    – flywire
    Oct 2, 2022 at 5:56
  • The first example does not work for me on MacOS with Python 3.11.4, openpyxl==3.1.2. The second example does work Mar 14 at 19:11
4

There is no method to do this. At the moment the best approach would probably be to set the style for all the relevant columns or rows

style = Style(…)
for col in 'ABCD':
     ws._styles[col] = style

I think we'll be working on improving handling styles in coming releases.

4
  • 1
    Note: ws._styles should index "col" instead of "A" Sep 19, 2016 at 2:42
  • Well?! The question certainly remains relevant: How to apply a style to every cell in a worksheet. In fact, yesterday I was looking for an answer to exactly that question. Also, it is conceivable that somebody, even today, would have a similar software setup. Conclusion: The note does not hurt. Sep 19, 2016 at 14:47
  • The note relies on private API which is no longer available and would never have really worked anyway because of the way styles for rows and columns are implemented in OOXML. Sep 20, 2016 at 10:23
  • 1
    SOLVED: stackoverflow.com/a/50195113/4539999
    – flywire
    Oct 2, 2022 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.