gpt4 book ai didi

python - 将条件格式应用于excel中的整行

转载 作者:行者123 更新时间:2023-12-04 10:05:55 26 4
gpt4 key购买 nike

我是python初学者。
我正在尝试使用 pandas 和 xlsxwriter 为文件夹中的所有 excel 文件设置相同的条件格式。
这些文件的结构如下:

A    | B   | C   | ... | K
ID | ... | ... | ... | Risk
1 | ... | ... | ... | High
2 | ... | ... | ... | Medium
3 | ... | ... | ... | High
4 | ... | ... | ... | Low

我想根据列 k risk 中的值设置相同的格式(对于整行) .
import os, glob
import pandas as pd
import numpy as np
import xlsxwriter
import os

#Set the input directory
myFolder = r"MyFolderPath"
os.chdir(myFolder)

#generate a list of excel files using the glob method
fileList = glob.glob("*.xlsx")

#for each element within the list apply the conditional formatting
for elem in fileList:
df = pd.read_excel(elem)
writer = pd.ExcelWriter(df)
df.to_excel(writer, sheet_name = 'sheet_1')

workbook = writer.book

format1 = workbook.add_format({'bg_color': 'red'})
format2 = workbook.add_format({'bg_color': 'yellow'})

worksheet = writer.sheets['sheet_1']

worksheet.conditional_format('K2:K100', {'type': 'cell',
'criteria': 'equal to',
'value': '"high"',
'format': format1})
worksheet.conditional_format('K2:K100', {'type': 'cell',
'criteria': 'equal to',
'value': '"medium"',
'format': format2})
workbook.close

print ("Done")



我没有错误,但脚本没有修改文件。

最佳答案

您需要将类型更改为公式,并将条件更改为所需条件。检查此示例以了解您应该如何编写它:

import pandas as pd

df = pd.DataFrame({'ID': [1,2,3,4],
'B': ['a','b','c','d'],
'Risk': ["High","Medium","High","Low"]})

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

format_red = workbook.add_format({'bg_color': '#FFC7CE'})
format_yellow = workbook.add_format({'bg_color': '#FFEB9C'})
format_green = workbook.add_format({'bg_color': '#C6EFCE'})

worksheet.conditional_format('A2:C5', {'type': 'formula',
'criteria': '=$C2="High"',
'format': format_red})

worksheet.conditional_format('A2:C5', {'type': 'formula',
'criteria': '=$C2="Medium"',
'format': format_yellow})

worksheet.conditional_format('A2:C5', {'type': 'formula',
'criteria': '=$C2="Low"',
'format': format_green})

writer.save()

输出:

enter image description here

关于python - 将条件格式应用于excel中的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61590282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com