How set style for cell?

Issue #186 resolved
Magister_Yoda
created an issue

Hi!

font = Font()
font.name = 'Consolas'
font.size = 10
style = Style()
style.font = font

how set this style for cell?

ws.cell('B1').style = style

not work

Comments (8)

  1. Adam Morris

    Try using a function like this:

    def copyStyle(toStyle, fromStyle):
        """Simple way to copy styles for openpyxl."""
        toStyle.font = deepcopy(fromStyle.font)
        toStyle.fill = deepcopy(fromStyle.fill)
        toStyle.borders = deepcopy(fromStyle.borders)
        toStyle.alignment = deepcopy(fromStyle.alignment)
        toStyle.number_format = deepcopy(fromStyle.number_format)
        toStyle.protection = deepcopy(fromStyle.protection)
    
    # Then:
    font = Font()
    font.name = 'Consolas'
    font.size = 10
    style = Style()
    style.font = font
    
    copyStyle(ws.cell('B1').style, style)
    
  2. CharlieC

    Starting with v2.0 styles are immutable so the suggestions won't work quite as advertised.

    There is no function for applying the same style to multiple cells at once but you could do this within a range or simply iterate over the the cells. Styles can also be applied to rows and columns or even groups of columns.

    The current idiom would be

    from openpyxl.styles import Font, Style
    ft = Font(name='Consolas', size=10)
    st = Style(font=ft)
    
    ws['B1'].style = st
    
  3. CharlieC

    Actually, you were provided with workable answers last year. Posting questions like this on the bugtracker is not necessarily the best place, the mailing list might be better. But this also how things are in the open source world: every project depends upon volunteers being prepared to look at things.

  4. Log in to comment