可以参考的网站
- Working with Conditional Formatting
https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html - The Format Class
https://xlsxwriter.readthedocs.io/format.html#format - Example: Conditional Formatting
https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format - pandas.ExcelWriter
https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html
Demo
例如,为奇偶行设置不同的颜色
df = ...
writer = pd.ExcelWriter('tosave.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# 期望的设定格式
format1 = workbook.add_format({'bg_color': '#f0a1a8',
'font_color': '#9C0006'})
# 对奇数行设置颜色
worksheet.conditional_format('B2:I20', {'type': 'formula',
'criteria': '=mod(row(),2)=1',
'format': format1})