4

I'm avoiding using any other set of modules.

What I am trying to do is set a cell's color in Excel, using the pywin32 libary. So far I've found how to get the cells color:

print xl.ActiveSheet.Cells(row, column).interior.color

and you can set it simply by assigning it in a similar fashion:

xl.ActiveSheet.Cells(row, column).interior.color = 0 #black

My question is how to set the cell's colour in RGB?

I need something called a ColorTranslator to OLE , but I don't know how to access system.drawing since it seems like it's a .NET thing. http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.toole.aspx

TankorSmash
  • 12,186
  • 6
  • 68
  • 106

2 Answers2

13

interior.color expects a hex value in BGR. If you want to specify in RGB form below code can be used.

def rgb_to_hex(rgb):
    '''
    ws.Cells(1, i).Interior.color uses bgr in hex

    '''
    bgr = (rgb[2], rgb[1], rgb[0])
    strValue = '%02x%02x%02x' % bgr
    # print(strValue)
    iValue = int(strValue, 16)
    return iValue

ws.Cells(1, 1).Interior.color = rgb_to_hex((218, 36, 238))
Chen Du
  • 130
  • 2
  • 10
Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26
  • 3
    Seems like the colors are reversed in excel. Passing (255,255,0) shows a blue in the sheet: (0,255, 255). I guess the color is `BGR`. Thanks for the help. – TankorSmash Jul 12 '12 at 17:25
11

Excel can use an integer calculated by the formula Red + (Green * 256) + (Blue * 256 * 256)

def rgbToInt(rgb):
    colorInt = rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
    return colorInt

ws.Cells(row,col).Font.Color = rgbToInt((255,255,128))
GdD
  • 221
  • 2
  • 8