Search code examples
pythonexceltkinteropenpyxl

fail getting a back ground color with openpyxl


I search that the background color is bgcolor and the library has an alias so its end_color but when i get it with the following function it tells that values must bne of type str

    def obtenerColor(self, columna):
        celda = self.excel.hoja.cell(row= 1, column=columna)

        if celda.fill.end_color.rgb is not None:
            color = celda.fill.end_color.rgb
        else:
            color = '00000000'

        return color

i want to know the color of the background cell to use it late in a tkinter.Frame(window, bg=color)

y tried with the foreground color but when it let me a color that is not rgb so i coundnt use without transform it with the following function

def cambioHexARGB(color):
    rgb = tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))
    colorRGB = '#%02x%02x%02x' % rgb
    return colorRGB

but it print a strange color that is not the one that has to be (obv cause i want the bg color and i pick the fg color)


Solution

  • end_color is not guaranteed to return a value, you would then need to try start_color instead or you may be better off to use fgColor as that should always return the fill color of a cell.

    The value will then usually be in all of the following fields .index, .rgb and .value as aRGB in string format so it is 8 characters, 4 couplets.

    Therefore a returned value may be '00E6F0FA', in this case your conversion to integer RGB function cambioHexARGB using the first 3 couplets '00E6F0' will give you an incorrect value. The first couplet should be ignored so your code would need to change to

    tuple(int(color[i:i+2], 16)  for i in (2, 4, 6))
    

    giving a returned int RGB as 230,240,250