pythonpython-3.xfontsopenpyxl

Issue with openpyxl.styles module in python, unable to set font attribute


Having an issue using the openpyxl.styles.Font() function, I'm seeing it taught this way in the documentation as well, so unsure what might have changed.

>>> import openpyxl
>>> from openpyxl.styles import Font

>>> wb = openpyxl.Workbook()
>>> sheet = wb.get_sheet_by_name('Sheet')

>>> font_style = Font(sz=30, i=True)

>>> sheet['A1'].font = font_style

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    sheet['A1'].font = font_style
AttributeError: can't set attribute

I've also tried it this way:

sheet['A1'].font = Font(size=30, italic=True)
sheet['A1'].font = Font(sz=30, i=True)

Getting this error message when I try to set a cell to a font style, nothing seems to be working.

Any suggestions are appreciated, thank you.


Solution

  • I think, you use an old version of openpyxl because I can't reproduce your problem with the version v2.5.8.

    Nevertheless, there is something curious: you are trying to get the "Sheet" worksheet from a newly-crated workbook. So this sheet doesn't exist.

    You should try:

    import openpyxl
    
    from openpyxl.styles import Font
    
    wb = openpyxl.Workbook()
    sheet = wb.create_sheet('Sheet')
    font_style = Font(sz=30, i=True)
    sheet['A1'].font = font_style
    

    This creates a new worksheet named "Sheet" and defines the font of the first cell.