Alter the style of all cells with openpyxl

Question:

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.

Asked By: Mike

||

Answers:

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.

Answered By: Charlie Clark

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

Answered By: flywire
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.