业务场景:当我们对Excel表格标记了不同颜色,我们怎么统计不同颜色的文本框的数量呢?
解决思路:
- 读取文本框的颜色种类颜色有哪些
- 统计每个种类的个数
from openpyxl import load_workbook
def count_highlighted_colors_in_column(file_path, sheet_index, column_index):
# 加载 Excel 文件
wb = load_workbook(file_path)
ws = wb.worksheets[sheet_index]
# 创建一个空字典来存储不同颜色单元格的数量
color_count = {}
# 遍历指定列的单元格并统计不同颜色单元格的数量
for row in ws.iter_rows(min_row=1, min_col=column_index, max_col=column_index):
for cell in row:
if cell.fill.start_color.rgb is not None:
color = cell.fill.start_color.rgb
if color not in color_count:
color_count[color] = 1
else:
color_count[color] += 1
return color_count
# 调用函数并打印结果
file_path = "your_path.xlsx" # 替换为你的 Excel 文件路径
sheet_index_1 = 3 # 从 0 开始索引,所以第四个表的索引为 3
column_index_1 = 7 # 要取出的列数
result_1 = count_highlighted_colors_in_column(file_path, sheet_index_1, column_index_1)
print("【观点】列不同高亮颜色单元格的数量:", result_1)