【问题标题】:Pandas Conditional Formatting Removed in Excel在 Excel 中删除 Pandas 条件格式
【发布时间】:2018-12-18 18:01:20
【问题描述】:

这是我第一次使用 Python 使用 Pandas 模块格式化 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 和 Excel 2016。任何机构有任何建议的解决方案?

谢谢!

【问题讨论】:

  • 你能试试这个worksheet.conditional_format('B2:B8', {'type': '3_color_scale'})看看它是否能正常工作吗?
  • 可能你可以看看here
  • 不幸的是,@pygo,上面的代码行没有工作。但是,我没有收到错误。格式根本没有翻译。另一页也对我没有用处。不过感谢您的尝试!

标签: python excel pandas


【解决方案1】:

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

如果您更改该设置,您的程序将按预期运行。这是一个例子:

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()

输出:

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2017-12-02
    • 2020-11-16
    相关资源
    最近更新 更多