pandas XlsxWriter:为单元格添加颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38632753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XlsxWriter: add color to cells
提问by ldevyataykina
I try to write dataframe to xlsx and give color to that. I use
我尝试将数据帧写入 xlsx 并为其赋予颜色。我用
worksheet.conditional_format('A1:C1', {'type': '3_color_scale'})
But it's not give color to cell. And I want to one color to this cells.
I saw cell_format.set_font_color('#FF0000')
but there is don't specify number of cells
但它不是给细胞颜色。我想给这个单元格一种颜色。我看到了,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()
I need to give color to A1:C1
, but I should give name
to cell. How can I paint several cells of my df?
我需要给 颜色A1:C1
,但我应该给name
单元格。如何绘制 df 的多个单元格?
回答by Giordano
The problem is that worksheet.write('A1:C1', 'Ray', format)
is used only to write a single cell.
A possible solution to write more cells in a row, is use write_row()
.
问题是worksheet.write('A1:C1', 'Ray', format)
它只用于写入单个单元格。连续写入更多单元格的可能解决方案是使用write_row()
。
worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3'], format)
Remember that write_row()takes a list of string to write in cells.
请记住write_row()需要一个字符串列表来写入单元格。
If you use worksheet.write_row("A1:C1", 'Ray', format)
, you have Rin the first cell, ain second and yin the third.
如果您使用worksheet.write_row("A1:C1", 'Ray', format)
,则第一个单元格中为R,第二个单元格中为a,第三个单元格中为y。