excel - python pandas to_excel设置单元格背景颜色

标签 excel pandas colors

我经常看到 worksheet.conditional_format() ,但是如何进行无条件格式化?
我一直在使用一个几乎总是正确的条件......值(value)!= 2147483647(一些值(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.
我认为我的问题很有值(value),因为其他人也一定有这个问题。
但是我没有找到好的解决方案。
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
Styler 创建一个 HTML 表格
我很失望。

最佳答案

看起来最好的选择是使用格式再次将数据写入工作表。
我不知道两次写入数据是否有任何危害。
这可以进行无条件格式化,但会写入两次数据。为了避免两次写入值, 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)

关于excel - python pandas to_excel设置单元格背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68825987/

相关文章:

python - 如何将数据帧输出插入到mysql

python - 如何将整数类型的列转换为python中的日期时间类型?

javascript - 合并具有不同颜色的网格

python - 如何知道 opencv 上是否检测到颜色

VBA - 将字符串转换为算术运算符

vba - 循环VBA后变量值被遗忘

vba - 如何将 3 个 VBA 命令合并为一个?设置无绝对引用的打印范围

c# - 保存到现有的 excel 文件而不打开新的 excel 文件

python - 在 Pandas 列上使用字典吗?

colors - 将灰度值转换为 RGB 表示?