Setting styles in Openpyxl

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). There is a style.py class but it seems I can't set the style attribute of a cell, and I don't really want to start tinkering with the openpyxl source code.

Has anyone found a solution to this?


Solution 1:

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

from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.styles import Color, Fill
from 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'

Solution 2:

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.

Solution 3:

For openpyxl version 2.4.1 and above use below code to set font color:

from openpyxl.styles import Font
from openpyxl.styles.colors import Color

ws1['A1'].font = Font(color = "FF0000")

hex codes for various colors can be found at: http://dmcritchie.mvps.org/excel/colors.htm