新手上路,大佬勿喷!
以下代码演示:
我们首先找出所有的红色区块。然后,对于每个红色区块,我们找到紧跟在它后面且长度相同的区块,并将这个区块的颜色改为黄色。最后,我们保存了修改过的工作簿。
先安装 需要用到的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')
先看演示文件内容:
跑一下看下效果