python处理表格-找出所有的自定义颜色区块,对于每个自定义颜色块,我们找到紧跟在它后面且长度相同的区块,并将这个区块的颜色改为另一种颜色,并保存

该代码示例展示了如何用Python的openpyxl库查找并替换Excel文件中特定颜色的单元格。程序首先识别所有红色填充的单元格,然后将紧跟其后且长度相同的区块颜色改为黄色。最后,保存修改后的工作簿。
摘要由CSDN通过智能技术生成

新手上路,大佬勿喷!

以下代码演示:

我们首先找出所有的红色区块。然后,对于每个红色区块,我们找到紧跟在它后面且长度相同的区块,并将这个区块的颜色改为黄色。最后,我们保存了修改过的工作簿。

先安装 需要用到的openpyxl

pip install openpyxl

 以下为主代码块,随意命名,测试文件为text.xlxs  输出文件为 modified.xlsx

from openpyxl import load_workbook
from openpyxl.styles import PatternFill

# Load your workbook
wb = load_workbook('test.xlsx')

# Select your sheet
ws = wb['Sheet1']  # Replace with your sheet name

red_blocks = []
current_block = []

# Go through all cells in the first column
for cell in ws['A']:
    # Check if the cell is filled with red color
    if cell.fill.start_color.index == "FFFF0000":  # Color code for red
        current_block.append(cell.row)
    elif current_block:  # If the cell is not red and there is a red block, finish the block
        red_blocks.append(current_block)
        current_block = []

# If the last cell is red, finish the last block
if current_block:
    red_blocks.append(current_block)

# Define yellow fill
yellow_fill = PatternFill(start_color="FFFFFF00",
                   end_color="FFFFFF00",
                   fill_type="solid")

# Find following blocks and apply yellow fill
for block in red_blocks:
    start = block[-1] + 1  # Start of following block is the row after the red block
    length = len(block)  # Number of following rows is the same as the number of red rows
    following_block = range(start, start + length)

    for row in following_block:
        for cell in ws[row]:
            cell.fill = yellow_fill

# Save the modified workbook
wb.save('modified.xlsx')

先看演示文件内容:

 跑一下看下效果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值