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