无法使用python xlsxwriter更改excel中的字体颜色

时间:2018-05-23 18:48:54

标签: python excel pandas

workb = xlsxwriter.Workbook('Newexcel1.xlsx')
worksheet1 = workb.add_worksheet("Sheet 1")

for row, row_data in enumerate(alldata):
    worksheet1.write_row(row + 1, 1, row_data)

cell_format.set_font_color('vbRed')


worksheet1.conditional_format('C2:C7', {'type':     'cell',
                                    'criteria': '==',
                                    'value': 'Data Matched!',
                                    'format': cell_format})

我正在尝试使用python写入excel文件。 alldata 是列表列表。问题是我想将数据匹配中的文本颜色更改为绿色和未匹配!红色,这没有发生。上面列出的代码没有显示任何错误,但是当我打开excel文件时,它要求我恢复以前的版本,因为新版本有xml错误。

alldata =     [['My Total', 'Data Matched!', '$824,499,658', '$824,499,658'], ['Second Total', 'Data Matched!', '$824,532,682.20', '$824,532,682.20'], ['Featured Articles', 'Data Matched!', '$391,153,610.55', '$391,153,610.55'], ['Ads Revenue', 'Data Not Matched!', '$825,513,740.17', '$825,582,419.92'], ['Company 1 Revenue', 'Data Not Matched!', '$824,765,286.03', '$824,833,965.78'], ['Company 2 Revenue', 'Data Not Matched!', '$176,767,751.61', '$239,939,801.89']]

1 个答案:

答案 0 :(得分:1)

在XlsxWriter中使用条件格式时,最好首先弄清楚要在Excel中执行的操作,然后将其传输到XlsxWriter。

在这种情况下,Excel不支持使用字符串进行单元格相等。相反,你必须使用"文本"有条件的(或可能是公式)。

以下是您的代码的简化版本,它修复了一些小问题并完成了您想要的操作:

import xlsxwriter

alldata = [['My Total', 'Data Matched!', '$824,499', '$824,499'],
           ['Second Total', 'Data Matched!', '$824,532', '$824,532'],
           ['Featured Articles', 'Data Matched!', '$391,153', '$391,610'],
           ['Ads Revenue', 'Data Not Matched!', '$825,513', '$825,492'],
           ['Company 1 Revenue', 'Data Not Matched!', '$824,263', '$824,965'],
           ['Company 2 Revenue', 'Data Not Matched!', '$176,711', '$239,801']]

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_column('C:C', 14)

cell_format = workbook.add_format()
cell_format.set_font_color('red')

for row, row_data in enumerate(alldata):
    worksheet.write_row(row + 1, 1, row_data)

worksheet.conditional_format('C2:C7', {'type': 'text',
                                       'criteria': 'begins with',
                                       'value': 'Data Matched!',
                                       'format': cell_format})

workbook.close()

输出:

enter image description here