我有一个excel文件。它有 C_ID、A_ID、ID_Comparison、C_Title、A_Title、Title_Comparisom 等列。比较列根据比较列有真或假。如果值为假,我想为比较列的单元格添加背景填充。我在一个 excel 文件中有很多工作表,在一个工作表中我有上面的列。我想为每张工作表迭代每张工作表我需要查看列以过滤比较列并进行操作并生成一个新的 Excel 文件。
将 pandas 导入为 pd
从 openpyxl.styles 导入 PatternFill
从 openpyxl.utils 导入 get_column_letter
with pd.ExcelFile(input file) as xls:
Dfs = {sheet_name: xls.parse(sheet_name) for sheet_name in xls.sheet_names}
对于sheet_name,dfs.items()中的df:
for col in df.filter(regex='_Comparison').columns:
df[col] = df[col].map({True: "True", False: "False"})
with pd.ExcelWriter("output.xlsx", engine="openpyxl") as writer:
# Export DataFrame content
df.to_excel(writer, sheet_name=sheet_name, index=False)
# Set background colors depending on cell values
sheet = writer.sheets[sheet_name]
column_letter = get_column_letter(sheet[f'{col}1'].column)
for cell, in sheet[f'{column_letter}2:{column_letter}{len(df) + 1}']:
value = df[col].iloc[cell.row - 2] # value is "True" or "False"
cell.fill = PatternFill("solid", start_color=("5cb800" if value == "True" else 'ff2800'))
这段代码每次在比较列上循环时都会覆盖输出文件。我想像输入文件一样获取输出文件。相同顺序的所有列只是比较列将用红色 bg 填充假值。