【问题标题】:python panas to_excel set cells background colorpython pandas to_excel设置单元格背景颜色
【发布时间】:2021-10-19 20:55:42
【问题描述】:

我经常看到 worksheet.conditional_format(),但我如何进行无条件格式化?
我一直在使用一个几乎总是正确的条件... value!=2147483647(some value)

worksheet.conditional_format('B3:K12', 
      {'type':'cell', 'criteria':'!=', 'value':2147483647, 'format':my_format})

我看到一些函数似乎在您编写单元格时设置格式,但我使用的是 Pandas,希望我可以在运行 df.to_excel(..) 后在 DataFrame 或工作表上设置格式可以用conditional_format()

worksheet.set_row(   row,        height, cell_format, options)
worksheet.set_column(first, last, width, cell_format, options)
#  But I want to set a subset not a whole row/column
worksheet.write       (0, 0, 'Foo', cell_format)
worksheet.write_string(1, 0, 'Bar', cell_format)
worksheet.write_number(2, 0, 3,     cell_format)
worksheet.write_blank (3, 0, '',    cell_format)
#  And I'm not looking forward to writing every value myself.

我认为我的问题很有价值,因为其他人一定也有这个问题。
但是我没有找到好的解决方案。

https://xlsxwriter.readthedocs.io/working_with_pandas.html
XlsxWriter 和 Pandas 几乎不支持格式化数据帧中的输出数据,除了默认格式,例如标题和索引单元格以及包含日期或日期时间的任何单元格。此外,无法格式化已应用默认格式的任何单元格。
#
如果您需要非常可控的数据帧输出格式,那么您最好直接使用 Xlsxwriter 处理从 Pandas 获取的原始数据。但是,一些格式选项是可用的。

https://www.ojdo.de/wp/2019/10/pandas-to-excel-with-openpyxl/
# 对于一般样式,必须单独遍历所有单元格

https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
样式器创建一个 HTML 表格

我很失望。

【问题讨论】:

标签: excel pandas colors


【解决方案1】:

看起来最好的选择是使用格式将数据再次写入工作表。
我不知道两次写入数据是否有任何危害。
这可以进行无条件格式化,但会写入两次数据。
为了避免两次写入值,to_excel() 可以写入一个子集,然后添加格式化项目。
但是,如果您想做多个单元格.. 然后您编写没有值的格式。似乎不一致。为什么我不能向没有值的单元格写入格式?

import pandas as pd
df = pd.DataFrame(data={ 'col1':['col1v0','col1v1'], 'col2':['col2v0','col2v1'], })
with pd.ExcelWriter('output.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')
    #
    workbook  = writer.book
    format_bg_red = workbook.add_format({'bg_color': 'red'})
    #
    worksheet = writer.sheets['Sheet1']
    worksheet.write('B2', 'NewItem', format_bg_red) # write again
    worksheet.set_row(1, height=22, cell_format=format_bg_red)
猜你喜欢
  • 2010-11-21
  • 2015-01-01
  • 2012-06-06
  • 2019-10-21
  • 2017-02-08
  • 2016-12-18
  • 2018-06-15
  • 2013-07-19
  • 2011-10-10
相关资源
最近更新 更多