Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

python - Setting a cell's fill RGB color with pywin32 in excel?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...