写入 excel 文件时用 python 更改文本颜色

change the text color with python when write the excel file

将数据帧写入 excel 文件时,如何更改某行的字体颜色?

这是示例数据框。

如果金额<0,则除姓名外,整行文字颜色变为红色

这是一个示例数据框,您可以将其插入 excel,并在帐户列中使用正确的颜色编码

import openpyxl
# Sample dataframe
data = {'name': ['A', 'B', 'C', 'D', 'E'],
        'Amount':[7, -2, 5, -1, 0], 
        'unit_price': [600, 500, 440, 510, 350], 
        'total_price': [4200, -1000, -2200, -510, 0]}
df=pd.DataFrame(data)

wb = openpyxl.Workbook()
ws = wb.active

#Write data
from openpyxl.utils.dataframe import dataframe_to_rows
rows = dataframe_to_rows(df, index=False)
for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
         ws.cell(row=r_idx, column=c_idx, value=value)

#Check and set format to RED
for row in range(0, df.shape[0]):
    if df.iloc[row,1] < 0:
        for col in range(0,df.shape[1]):
            ws.cell(row+2, col+1).font = openpyxl.styles.Font(color='FF0000')

wb.save("output_file.xlsx")