python - 如何使用 Python 更改基于 excel 中文本的颜色?

标签 python xlwt

在 Excel 单元格文本中,从通过到失败会有所不同。我必须分别为通过(通过/通过/通过)提供绿色背景颜色,为失败(失败/失败/失败)提供红色背景颜色。如何根据文本更改颜色?

我的脚本

import xlwt

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Testing')
worksheet.write_merge(5, 5, 1, 1,'S.No')
worksheet.write_merge(5, 5, 2, 2,'Test Case Description')
worksheet.write_merge(5, 5, 3, 3,'Status')
worksheet.write_merge(5, 5, 4, 4,'Remarks')
worksheet.write_merge(6, 6, 1, 1,1)
worksheet.write_merge(7, 7, 1, 1,1)
worksheet.write_merge(6, 6, 2, 2,'Verify Transferring rate')
worksheet.write_merge(7, 7, 2, 2,'Verify Receiving rate')
worksheet.write_merge(6, 6, 3, 3,'Pass')
worksheet.write_merge(7, 7, 3, 3,'Fail')
workbook.save('testexcel.xls')

@亨利:

修改后的代码:

import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Status')

passed = xlwt.easyxf('back_color green')
failed = xlwt.easyxf('back_color red')


color = (passed if passorfail in ['pass','Passed','passed'] else
    (failed if passorfail in ['fail','Failed','failed'] else xlwt.easyxf()))

worksheet.write_merge(6, 6, 3, 3,passorfail, style = color)

workbook.save('passfail2.xls')
print "Completed"

执行时会抛出错误?如何解决此错误?

Traceback (most recent call last):
  File "G:\airspan_eclipse\Excel_Gen\passfail2.py", line 5, in <module>
    passed = xlwt.easyxf('back_color green')
  File "C:\Python27\lib\site-packages\xlwt\Style.py", line 704, in easyxf
    field_sep=field_sep, line_sep=line_sep, intro_sep=intro_sep, esc_char=esc_char, debug=debug)
  File "C:\Python27\lib\site-packages\xlwt\Style.py", line 632, in _parse_strg_to_obj
    raise EasyXFCallerError('line %r should have exactly 1 "%c"' % (line, intro_sep))
xlwt.Style.EasyXFCallerError: line 'back_color green' should have exactly 1 ":"

最佳答案

您可以使用 easyxf 创建样式然后将它们作为参数传递给您的 write 方法。

例如:

style_pass = xlwt.easyxf('pattern: pattern solid, fore_colour green;')
style_fail = xlwt.easyxf('pattern: pattern solid, fore_colour red;')
worksheet.write_merge(6, 6, 3, 3,'Pass', style=style_pass)
worksheet.write_merge(7, 7, 3, 3,'Fail', style=style_fail)

关于python - 如何使用 Python 更改基于 excel 中文本的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673368/

相关文章:

Python:拆分numpy数组

excel - Pandas to_excel( ) 输出 float 不正确

python - 使用 Python 将 mysql 表详细信息转换为 Excel (.xls) 或逗号分隔文件 (.csv)

Python Excel 日期/时间读入问题

python - 使用python复制文件

python - 模块 'skfeature.function.similarity_based.fisher_score' 没有属性 'feature_ranking'

python - 如何使用 xlrd、xlwt 和 xlutils 将 "existing"工作表添加到工作簿

python - 使用 xlwt 优化 xls 文件中的添加行

python - 在类的字段上对 dict() 进行排序

Python 插件系统 - HOWTO