我对Python相当陌生,我无法弄清楚: 我正在尝试根据单元格值格式化整个行。
我尝试了这段代码,它对文件绝对没有任何作用:
writer = pd.ExcelWriter("Classeur.xlsx")
df.to_excel(writer, sheet_name="Feuil1")
writer.save()
workbook=writer.book
worksheet=writer.sheets['Feuil1']
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
worksheet.conditional_format('A2:C5',
{"type": "formula",
"criteria": '="$B"&ROW()="FR"',
"format": format1
}
)
workbook.close()
我的文件有三列:Product , Country , Sales
,我希望对法国所在的所有行进行着色。
谢谢。
答案 0 :(得分:0)
u可以使用以下代码进行测试:
df= pd.DataFrame([[0,'A',1],[1,'FR',2],[2,'B',3],[3,'C',5],[4,'FR',7]])
writer = pd.ExcelWriter("Classeur.xlsx")
df.to_excel(writer, sheet_name="Feuil1",header =False, index = False)
workbook=writer.book
worksheet=writer.sheets['Feuil1']
format1 = workbook.add_format({'bg_color': '#FFC7CE','font_color': '#9C0006'})
worksheet.conditional_format('A2:C5', {'type': 'cell','criteria': '==','value': '"FR"',"format": format1})
workbook.close()
writer.save()
或使用:
df= pd.DataFrame([[0,'A',1],[1,'FR',2],[2,'B',3],[3,'C',5],[4,'FR',7]])
writer = pd.ExcelWriter("Classeur.xlsx")
df.to_excel(writer, sheet_name="Feuil1",header =False, index = False)
workbook=writer.book
worksheet=writer.sheets['Feuil1']
format1 = workbook.add_format({'bg_color': '#FFC7CE','font_color': '#9C0006'})
worksheet.conditional_format('B2:B5', {'type': 'formula','criteria': '=B2="FR"','format': format1})
workbook.close()
writer.save()
如果要将数据框的列名和索引保存为excel,可以删除header =False and index = False
。
如果要对整行进行着色,则可以按照建议的here使用excel中的INDIRECT()
函数。
df= pd.DataFrame([[0,'A',1],[1,'FR',2],[2,'B',3],[3,'C',5],[4,'FR',7]])
writer = pd.ExcelWriter("Classeur.xlsx")
df.to_excel(writer, sheet_name="Feuil1",header=False,index=False)
writer.save()
workbook=writer.book
worksheet=writer.sheets['Feuil1']
format1 = workbook.add_format({'bg_color': '#FFC7CE','font_color': '#9C0006'})
worksheet.conditional_format('A2:C5', {"type": "formula","criteria": '=INDIRECT("B"&ROW())="FR"',"format": format1})
workbook.close()
writer.save()