简体   繁体   中英

How to change color of a cell in Excel file with Iron Python?

How do I change cell background color in Excel from Iron Python?

I tried following code:

def rgb_to_hex(rgb):
    strValue = '%02x%02x%02x' % rgb
    iValue = int(strValue, 16)
    return iValue

worksheet.range["H6"].interior.color = rgb_to_hex((255,255,0))

But does not work. It is giving HResult error

I am not familiar with Iron Python, but in C# I do the following:

Range colorCells = WS.get_Range(WS.Cells[row.Row, locCol], WS.Cells[row.Row, locCol + locWid]);
colorCells.Interior.Color = System.Drawing.ColorTranslator.ToOle(color);

My guess is that Tim has the right suggestion, you need to use a different way to convert your RGB to a color that interior.color can accept.

In my C#, it is assigning the color as an int.

public static int ToOle(Color c);

I've managed to enter the color in two ways:

  1. Using ColorIndex

https://docs.microsoft.com/en-us/office/vba/api/excel.colorindex

 worksheet.Range["H6"].Interior.ColorIndex = 3 

  1. With System.Drawing.ColorTranslator.ToOle(color), like Owen Ivory suggested

 clr.AddReference('System.Drawing') from System.Drawing import Color, ColorTranslator def rgbForExcel(r, g, b): return ColorTranslator.ToOle(Color.FromArgb(r, g, b)) worksheet.Range["H6"].Interior.Color = rgbForExcel(255, 50, 0) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM