我有一个包含3列的.xlsx文件。
id name age
1 jon 10 #jon cell is red
2 bob 54 #bob cell is red
3 rob 77
4 sal 22 #sal cell is red
5 wil 47
6 nia 32
在我的column 'name' jon ,bob, sal cell are red colored
中,列'name'的其余单元格为绿色。
我想找到red colored cells
的计数,即本例3
。
这只是一个例子,我有.xlsx文件,其行数超过1000行,手动计算红色单元格非常困难。
我尝试使用openpyxl和xlrd但却找不到
任何线索都会受到赞赏,提前谢谢
答案 0 :(得分:0)
我看了Here
首先,我们需要加载工作簿,然后使用该工作簿中的选定工作表,为此我们执行以下操作:
import openpyxl as px
#Loading the workbook into python
wb = px.load_workbook('FileName.xlsx')
#Selecting Active Sheet
sheet = wb.get_sheet_by_name('Sheet1')
第二个答案(在链接中)非常有用 - 可以通过引用执行以下操作的颜色index来获取单元格颜色的HEX代码:
i = sheet['A1'].fill.start_color.index #Grabbing colour at [A1]
index_colours = px.styles.colors.COLOR_INDEX
result = str(index_colours [i])
result= "#"+result[2:]
print result
#>>>#HEXCODE
您可以使用此功能,并在阅读excel文件后将所有代码添加到列表中,例如:
colour_list = []
index_colours = px.styles.colors.COLOR_INDEX
for row in range(1,all_rows):
i = sheet['B' + str(row)].fill.start_color.index
result = str(index_colours [i])
result= "#"+result[2:]
colour_list.append(result)
并计算引用红色的HEX代码
red = '#FF0000'
print colour_list.count(red)
#>>> 3
答案 1 :(得分:0)
这是使用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
答案 2 :(得分:0)
这是解决方案
'TypeError: tuple indices must be integers or slices, not str': result = str(index_colours [i])
实际上,i
或颜色索引返回为 String
。因此,当我们将它作为 index_colors
的索引传递时,我们会得到上述错误。需要将i
转换成int
,如下图:
result = str(index_colors[int(i)])