python - XlsxWriter:为单元格添加颜色

标签 python pandas xlsxwriter

我尝试将数据帧写入 xlsx 并为其赋予颜色。 我用的是

worksheet.conditional_format('A1:C1', {'type': '3_color_scale'})

但它不会给单元格赋予颜色。我想为这个单元格设置一种颜色。 我看到cell_format.set_font_color('#FF0000') 但没有指定单元格数量

sex = pd.concat([df2[["All"]],df3], axis=1)
excel_file = 'example.xlsx'
sheet_name = 'Sheet1'

writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
sex.to_excel(writer, sheet_name=sheet_name, startrow=1)
workbook = writer.book
worksheet = writer.sheets[sheet_name]

format = workbook.add_format()

format.set_pattern(1)
format.set_bg_color('gray')
worksheet.write('A1:C1', 'Ray', format)

writer.save()

我需要为 A1:C1 提供颜色,但我应该为单元格提供name。如何绘制 df 的多个单元格?

最佳答案

问题是 worksheet.write('A1:C1', 'Ray', format) 仅用于写入单个单元格。 连续写入更多单元格的可能解决方案是使用 write_row()

worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3'], format)

请记住,write_row() 采用要写入单元格的字符串列表。

如果您使用 worksheet.write_row("A1:C1", 'Ray', format),则第一个单元格中有 Ra 在第二个,y 在第三个。

关于python - XlsxWriter:为单元格添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632753/

相关文章:

python - 如何在 pandas 数据框上计算一天的小时数

python - 乘以包含 NaN 的 Pandas 系列行

python - Pandas Excel 到 DF 抛出意外的关键字参数 'index' 错误

python - Pandas - 使用算术将新行添加到数据框

python - 为什么我不能在 pandas 为我创建的 xlsxwriter 对象上卡住 Pane ?

python - 为什么放大绘图时 x 轴的时间存在差异

python - 用美汤加父标签

python - 如何使用 python 以编程方式创建 Google 表单?是否可以通过应用程序脚本和 python 接口(interface)或类似的东西来做到这一点?

python - xlsxwriter 和 xlrd 问题 - xlsx 文件在一台计算机上保存为 ZIP,但在另一台计算机上保存其他前 4 个字节

python - Excel 列以通用方式进行比较并用某种颜色突出显示差异