使用python从xlsx获取单元格的颜色

时间:2019-03-12 13:41:52

标签: python excel

我对python真的很陌生,但是我想从xlsx获取python给定单元格的颜色。我戴着读取xlsx的零件,但是如何获得A3电池的背景色呢?

import xlrd

workbook = xlrd.open_workbook('67.xlsx')
worksheet = workbook.sheet_by_name('Oldal1')
# read a cell
cell = worksheet.cell(2,2)
#print cell
print cell.value 

2 个答案:

答案 0 :(得分:1)

Always a solution out there, somewhere in the deep ocean of SO:

def getBGColor(book, sheet, row, col):
    xfx = sheet.cell_xf_index(row, col)
    xf = book.xf_list[xfx]
    bgx = xf.background.pattern_colour_index
    pattern_colour = book.colour_map[bgx]

    #Actually, despite the name, the background colour is not the background colour.
    #background_colour_index = xf.background.background_colour_index
    #background_colour = book.colour_map[background_colour_index]

    return pattern_colour

Oh, wait. this is even better!

编辑

这是完整的代码:

from xlrd import open_workbook

wb = open_workbook('cel_lis.xls', formatting_info=True)
sh = wb.sheet_by_name('Sheet1')


def getBGColor(book, sheet, row, col):
    xfx = sheet.cell_xf_index(row, col)
    xf = book.xf_list[xfx]
    bgx = xf.background.pattern_colour_index
    pattern_colour = book.colour_map[bgx]

    #Actually, despite the name, the background colour is not the background colour.
    #background_colour_index = xf.background.background_colour_index
    #background_colour = book.colour_map[background_colour_index]

    return pattern_colour


print("The RGB value of the cell is: {}".format(getBGColor(wb, sh, 0, 0)))

输出

The RGB value of the cell is: (255, 0, 0)

注意

  

我使用了类型为.xls的工作表,其名称为cel_lis.xls   名为Sheet1的工作表,其中第一个单元格A具有Red   背景颜色。

out

编辑2

要获得颜色name,可以使用webcolors

from webcolors import rgb_to_name

rgb_Col = getBGColor(wb, sh, 0, 0)
print("The RGB value of the cell is: {} which is equivalent to {}".format(rgb_Col, rgb_to_name(rgb_Col)))

输出

The RGB value of the cell is: (255, 0, 0) which is equivalent to red

答案 1 :(得分:0)

先前建议的解决方案仅适用于xls文件,不适用于xlsx文件。这产生一个NotImplementedError: formatting_info=True not yet implementedXlrd库仍未更新为不适用于xlsx文件。因此,您每次必须Save As并更改格式,这可能对您不起作用。
这是使用xlsx库的openpyxl文件的解决方案。 A2是我们需要找出其颜色代码的单元格。

import openpyxl
from openpyxl import load_workbook
excel_file = 'color_codes.xlsx' 
wb = load_workbook(excel_file, data_only = True)
sh = wb['Sheet1']
color_in_hex = sh['A2'].fill.start_color.index # this gives you Hexadecimal value of the color
print ('HEX =',color_in_hex) 
print('RGB =', tuple(int(color_in_hex[i:i+2], 16) for i in (0, 2, 4))) # Color in RGB