Setting styles in Openpyxl Setting styles in Openpyxl python python

Setting styles in Openpyxl


As of openpyxl version 1.5.7, I have successfully applied the following worksheet style options...

from openpyxl.reader.excel import load_workbookfrom openpyxl.workbook import Workbookfrom openpyxl.styles import Color, Fillfrom openpyxl.cell import Cell# Load the workbook...book = load_workbook('foo.xlsx')# define ws here, in this case I pick the first worksheet in the workbook...#    NOTE: openpyxl has other ways to select a specific worksheet (i.e. by name#    via book.get_sheet_by_name('someWorksheetName'))ws = book.worksheets[0]## ws is a openpypxl worksheet object_cell = ws.cell('C1')# Font properties_cell.style.font.color.index = Color.GREEN_cell.style.font.name = 'Arial'_cell.style.font.size = 8_cell.style.font.bold = True_cell.style.alignment.wrap_text = True# Cell background color_cell.style.fill.fill_type = Fill.FILL_SOLID_cell.style.fill.start_color.index = Color.DARKRED# You should only modify column dimensions after you have written a cell in #     the column. Perfect world: write column dimensions once per column# ws.column_dimensions["C"].width = 60.0

FYI, you can find the names of the colors in openpyxl/style.py... I sometimes I patch in extra colors from the X11 color names

class Color(HashableObject):    """Named colors for use in styles."""    BLACK = 'FF000000'    WHITE = 'FFFFFFFF'    RED = 'FFFF0000'    DARKRED = 'FF800000'    BLUE = 'FF0000FF'    DARKBLUE = 'FF000080'    GREEN = 'FF00FF00'    DARKGREEN = 'FF008000'    YELLOW = 'FFFFFF00'    DARKYELLOW = 'FF808000'


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 Workbookfrom openpyxl.styles import Font# Create workbookwb = Workbook()# Select active sheetws = wb.active()# Select cell A1cell = ws['A1']# Make the text of the cell bold and italiccell.font = cell.font.copy(bold=True, italic=True)


As of openpyxl 2.0, styles are immutable.

If you have a cell, you can (e.g.) set bold text by:

cell.style = cell.style.copy(font=cell.style.font.copy(bold=True))

Yes, this is annoying.