python - 如何使用 Python Pandas ExcelWriter 将单元格颜色添加到单元格范围?

标签 python pandas cell-formatting

我正在尝试使用 Python Pandas ExcelWriter 将背景单元格颜色添加到单元格范围。这是我到目前为止所拥有的:

 pivotChartsTab = pd.read_sql(sql4, conn)
 import pandas.io.formats.excel
 pandas.io.formats.excel.header_style = None
 pivotChartsTab.to_excel(writer, 'Pivot Tables', index=False)

#Format sheets
workbook = writer.book
format1 = workbook.add_format({'num_format': '#,##'}) 
format2 = workbook.add_format({'num_format': '#,##0.00'}) 
format3 = workbook.add_format({'num_format': '0%'})
format4 = workbook.add_format()
format4.set_pattern(1)
format4.set_bg_color('green')


#format Pivot Tables            
worksheet = writer.sheets['Pivot Tables']        
for i, col in enumerate(pivotChartsTab.columns):
    if i == 0:
        worksheet.set_column(i, i, 20)
    elif i == 1:
        worksheet.set_column(i, i, 15)
    elif i == 2:
        worksheet.set_column(i, i, 18)
    elif i == 3:
        worksheet.set_column(i, i, 20, format3)
    elif i == 4:
        worksheet.set_column(i, i, 25, format2)
    elif i == 5:
        worksheet.set_column(i, i, 25, format2) 
    elif i == 6:
        worksheet.set_column(i, i, 18, format3)
worksheet.write_row('A1:G1', format4)
writer.save()

所以本质上我正在尝试制作自己的客户标题样式。我希望背景色为绿色,行高为 25,但无法使着色工作,因此尚未尝试更改行高。

我觉得我错过了一些简单或基本的东西。感谢您的帮助。

最佳答案

这似乎有效,但我不确定如果单元格为空或空白等,它会如何 react ......

format4 = workbook.add_format({'bg_color': '#92D050'})
format5 = workbook.add_format({'text_wrap':True})

worksheet.set_row(0, 28, format5)
worksheet.conditional_format('A1:G1', {'type':'cell', 'criteria':'>=','value': 0, 'format':format4})

这会在我的标题上进行文本换行,行高为 28 以及我想要的颜色。

关于python - 如何使用 Python Pandas ExcelWriter 将单元格颜色添加到单元格范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328380/

相关文章:

python - Pandas 使用跨多个列的字典值相乘

python - 如何在 Pycharm 中使用 Pandas

ios - cell.detailTextLabel.text 为 NULL

ios - tableView cellForRowAt 返回自定义单元格错误

python - 有没有办法将 numpy.ndarray 的每个条目包装到一个单独的数组中?

python - Qlabel 中的像素图图像大小

python - 将列表合并为一个

python - 我如何将数据从数据框(在 python 中)插入到 greenplum 表?

python - 在Python 2.7中安装pandas v.0.13(开发版)

excel - 如何在整数时获取不带逗号的 Excel 单元格格式数字,在 float 时获取逗号后的两位数?