在Excel中删除了Pandas条件格式

时间:2018-12-18 02:38:35

标签: python excel pandas

这是我第一次使用Pandas模块使用Python格式化Excel电子表格。

我的代码如下所示:

writer = pd.ExcelWriter('%s.xlsx'%item,engine='xlsxwriter')
workbook  = writer.book
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                           'font_color': '#9C0006'})

final.to_excel(writer, '%s.xlsx'%item) # Output results to an excel file
#item is simply the name of the excel document.
#final is the name of the data frame I am working with.
worksheet = writer.sheets['%s.xlsx'%item ]
worksheet.conditional_format('A1:CG350', {'type':     'cell',
                                'criteria': 'containing',
                                'value':     'X ',
                                'format':    format1})
writer.save()

我的代码执行得很好。当我打开最终的Excel电子表格时,遇到以下错误消息:

Excel Error Message 1 Link

Excel Error Message 2 Link

基本上,Excel会强制我删除条件格式。我正在运行Python 3和Excel2016。有人有建议的解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

“包含”条件与“文本”类型而不是“单元格”相关。

如果更改,程序将按预期运行。这是一个示例:

import pandas as pd

final = pd.DataFrame({'Data': ['fox red', 'red fox', 'fox red', 'red fox']})

item = 'foo'
writer = pd.ExcelWriter('%s.xlsx'% item, engine='xlsxwriter')

workbook  = writer.book
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})

final.to_excel(writer, '%s.xlsx' % item)

worksheet = writer.sheets['%s.xlsx' % item]

worksheet.conditional_format('A1:CG350', {'type':     'text',
                                          'criteria': 'containing',
                                          'value':    'X ',
                                          'format':   format1})

writer.save()

输出:

enter image description here