在Python 3中使用xlsxwriter交替行颜色

时间:2016-09-20 15:48:57

标签: python python-3.x xlsxwriter

在Python3中使用xlsxwriter生成excel时,是否有人实现了交替行颜色?

while

这将设置每列的颜色。

2 个答案:

答案 0 :(得分:7)

没有什么可以阻止您手动设置格式,如下所示:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

data_format1 = workbook.add_format({'bg_color': '#FFC7CE'})
data_format2 = workbook.add_format({'bg_color': '#00C7CE'})

for row in range(0, 10, 2):
    worksheet.set_row(row, cell_format=data_format1)
    worksheet.set_row(row + 1, cell_format=data_format2)
    worksheet.write(row, 0, "Hello")
    worksheet.write(row + 1, 0, "world")

workbook.close()

这将使您的输出看起来如下:

Alternating row colours

答案 1 :(得分:0)

我认为这更干净-如果只想以两种颜色交替填写单元格

import xlsxwriter

workbook = xlsxwriter.Workbook('sample.xlsx')
worksheet = workbook.add_worksheet()

bg_format1 = workbook.add_format({'bg_color': '#78B0DE'}) # blue cell background color
bg_format2 = workbook.add_format({'bg_color': '#FFFFFF'}) # white cell background color

for i in range(10): # integer odd-even alternation 
    worksheet.set_row(i, cell_format=(bg_format1 if i%2==0 else bg_format2))
    # (or instead) if you want write and paint at once 
    # worksheet.write(i, 0, "sample cell text", (bg_format1 if i%2==0 else bg_format2))



workbook.close()

enter image description here