【发布时间】:2020-05-04 10:39:31
【问题描述】:
我是 python 初学者。 我正在尝试为使用 pandas 和 xlsxwriter 的文件夹中的所有 excel 文件设置相同的条件格式。 这些文件的结构如下:
A | B | C | ... | K
ID | ... | ... | ... | Risk
1 | ... | ... | ... | High
2 | ... | ... | ... | Medium
3 | ... | ... | ... | High
4 | ... | ... | ... | Low
我想根据 krisk 列中的值设置相同的格式(整行)。
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")
我没有错误,但脚本没有修改文件。
【问题讨论】:
标签: python pandas formatting conditional-formatting xlsxwriter