Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter the style of all cells with openpyxl

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.

like image 554
Mike Avatar asked May 23 '14 13:05

Mike


People also ask

How do I make my openpyxl faster?

Use just iterate through the rows. Using ws. cell in read-only mode will force openpyxl to start parsing the file again and again which is very slow. And if you have very large files read-only is the way to go.


2 Answers

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

like image 63
flywire Avatar answered Oct 16 '22 13:10

flywire


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['A'] = style

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

like image 44
Charlie Clark Avatar answered Oct 16 '22 13:10

Charlie Clark