Setting styles in Openpyxl

后端 未结 7 921
遇见更好的自我
遇见更好的自我 2020-12-01 03:17

I need advice on setting styles in Openpyxl.

I see that the NumberFormat of a cell can be set, but I also require setting of font colors and attributes (bold etc). T

7条回答
  •  庸人自扰
    2020-12-01 03:56

    As of openpyxl 2.0, setting cell styles is done by creating new style objects and by assigning them to properties of a cell.

    There are several style objects: Font, PatternFill, Border, and Alignment. See the doc.

    To change a style property of a cell, first you either have to copy the existing style object from the cell and change the value of the property or you have to create a new style object with the desired settings. Then, assign the new style object to the cell.

    Example of setting the font to bold and italic of cell A1:

    from openpyxl import Workbook
    from openpyxl.styles import Font
    # Create workbook
    wb = Workbook()
    # Select active sheet
    ws = wb.active()
    # Select cell A1
    cell = ws['A1']
    # Make the text of the cell bold and italic
    cell.font = cell.font.copy(bold=True, italic=True)
    

提交回复
热议问题