使用python为表格填充颜色

使用python为表格填充颜色

使用pandas,和openpyxl库。

需求说明:

如图所示我有这样的两列数据,一列是组ID,一列是物品名称。

我想使用python实现为不同的组填充颜色,便于区分查看,如图。

实现过程:

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import PatternFill

先使用panda提取将要填充的表格块位置

input_path = "demo.xlsx"

width = ["A", "B", "C"]  # 需要上色的宽度,对应表格中从”A“到”C“列
first_row = 2  # 需要上色的第一行,对应表格中第二行

# 找出不同组ID的位置,存入字典中。
df_data = pd.read_excel(input_path, sheet_name="Sheet1")
clusterIdl_list = df_data["clusterId"].tolist()
# 创建字典,key为clusterIdl_list的值,value为clusterIdl_list的索引列表
clusterIdl_dict = {
    
    }
for i in clusterIdl_list:
	clusterIdl_dict[i] = [rf"{
      
      j + first_row}" for j, x in enumerate(clusterIdl_list) if x == i]

print(clusterIdl_dict)
{0: ['2', '3'], 1: ['4', '5', '6'], 2: ['7'], 3: ['8'], 4: ['9', '10'], 5: ['11']}

clusterIdl_dict 中的key值记录了不同分组的ID,key对应value值表示表格中的对应行号。

# 字典的列表与width = "A","B","C"拼接组合
for key, value in clusterIdl_dict.items():
    clusterIdl_dict[key] = [f"{
      
      j}{
      
      k}" for j in width for k in value]

print(clusterIdl_dict)
{0: ['A2', 'A3', 'B2', 'B3', 'C2', 'C3'], 1: ['A4', 'A5', 'A6', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6'], 2: ['A7', 'B7', 'C7'], 3: ['A8', 'B8', 'C8'], 4: ['A9', 'A10', 'B9', 'B10', 'C9', 'C10'], 5: ['A11', 'B11', 'C11']}

此时clusterIdl_dict 中的key值记录了不同分组的ID,key对应value值表示表格中表格块位置。

有了对应的表格块位置,就可以进行填充了。

使用openpyxl填充颜色到表格块中

wb = load_workbook(filename=input_path)
# 使用第一个sheet作为工作簿
work = wb[wb.sheetnames[0]]
# 根据上面的work进行单元格选择
# 设置样式(填充色)
# 颜色必须使用hex 十六进制并且没有'#'符号 列举为黄色,粉色。
fill1 = PatternFill('solid', fgColor='fff68f')
fill2 = PatternFill('solid', fgColor='ffb6c1')
# 遍历字典
for key, value in clusterIdl_dict.items():
    # 单数填充fill1
    if key % 2 == 1:
        for i in value:
            work[i].fill = fill1
    # 双数填充fill2
    else:
        for i in value:
            work[i].fill = fill2

wb.close()
wb.save(output_path)

整合代码

def color_spray(input_path, output_path):
    """查位置模块"""
    width = ["A", "B", "C"]  # 需要上色的宽度,对应表格中从”A“到”C“列
    first_row = 2  # 需要上色的第一行,对应表格中第二行

    # 找出不同组ID的位置,存入字典中。
    df_data = pd.read_excel(input_path, sheet_name="Sheet1")
    clusterIdl_list = df_data["clusterId"].tolist()
    # 创建字典,key为clusterIdl_list的值,value为clusterIdl_list的索引列表
    clusterIdl_dict = {
    
    }
    for i in clusterIdl_list:
        clusterIdl_dict[i] = [rf"{
      
      j + first_row}" for j, x in enumerate(clusterIdl_list) if x == i]

    # 字典的列表与"A","B","C"拼接组合
    for key, value in clusterIdl_dict.items():
        clusterIdl_dict[key] = [f"{
      
      j}{
      
      k}" for j in width for k in value]

    """上色模块"""
    wb = load_workbook(filename=input_path)
    # 使用第一个sheet作为工作簿
    work = wb[wb.sheetnames[0]]
    # 根据上面的work进行单元格选择
    # 设置样式(填充色)
    # 颜色必须使用hex 十六进制并且没有'#'符号 列举为黄色,粉色。
    fill1 = PatternFill('solid', fgColor='fff68f')
    fill2 = PatternFill('solid', fgColor='ffb6c1')
    # 遍历字典
    for key, value in clusterIdl_dict.items():
        # 单数填充fill1
        if key % 2 == 1:
            for i in value:
                work[i].fill = fill1
        # 双数填充fill2
        else:
            for i in value:
                work[i].fill = fill2

    wb.close()
    wb.save(output_path)
    
    
if __name__ == "__main__":
    input_path = "demo.xlsx"
    output_path = "excel_col.xlsx"
    
    color_spray(input_path, output_path)

demo.xlsx 数据:

clusterId 物品
0 苹果
0 苹果
1 香蕉
1 香蕉
1 香蕉
2 栗子
3 花生
4 草莓
4 草莓
5 橘子

感兴趣的可以自己实验一下。如果对您有帮助,请您点赞收藏。

猜你喜欢

转载自blog.csdn.net/qq_58832911/article/details/127647302