【发布时间】:2018-05-31 03:01:19
【问题描述】:
我有一个 Excel 文件,其中的单元格具有背景颜色。我正在使用read_excel 将该文件读入pandas。有没有办法获取单元格的背景颜色?
【问题讨论】:
-
您可能需要考虑下拉到
xlrd(Pandas 使用它)来获取颜色信息。 -
如果我幸运的话会尝试回到这里!
我有一个 Excel 文件,其中的单元格具有背景颜色。我正在使用read_excel 将该文件读入pandas。有没有办法获取单元格的背景颜色?
【问题讨论】:
xlrd(Pandas 使用它)来获取颜色信息。
上面建议的解决方案仅适用于xls 文件,不适用于xlsx 文件。这引发了NotImplementedError: formatting_info=True not yet implemented。 Xlrd 库仍未更新以适用于 xlsx 文件。所以你必须Save As 并每次更改格式,这可能不适合你。
这是使用openpyxl 库的xlsx 文件的解决方案。 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
【讨论】:
我根据this link 编辑了上面@csaladenes 响应中的代码sn-p,它适用于我的xls 文件(原始导致所有单元格显示相同的颜色索引,尽管它们具有不同的背景颜色):
import xlrd
import numpy as np
wb = xlrd.open_workbook(file, formatting_info=True)
sheet = wb.sheet_by_name("mysheet")
bgcol=np.zeros([sheet.nrows,sheet.ncols])
for row in range(sheet.nrows):
for col in range(sheet.ncols):
c = sheet.cell(row, col)
cif = sheet.cell_xf_index(row, col)
iif = wb.xf_list[cif]
cbg = iif.background.pattern_colour_index
bgcol[row,col] = cbg
【讨论】:
from xlrd import open_workbook
wb = open_workbook('wb.xls', formatting_info=True)
sheet = wb.sheet_by_name("mysheet")
#create empy colormask matrix
bgcol=np.zeros([sheet.nrows,sheet.ncols])
#cycle through all cells to get colors
for row in range(sheet.nrows):
for column in range(sheet.ncols):
cell = sheet.cell(row, column)
fmt = wb.xf_list[cell.xf_index]
bgcol[row,column]=fmt.background.background_colour_index
#return pandas mask of colors
colormask=pd.DataFrame(bgcol)
但是,必须有更好的方法直接通过 pandas...
【讨论】: