Alternating row color using xlsxwriter in Python 3

r0xette picture r0xette · Sep 20, 2016 · Viewed 11.8k times · Source

Has anybody implemented alternating row color while generating excel using xlsxwriter in Python3?

data_format = workbook.add_format(
    {
        'bg_color': '#FFC7CE'
    })

worksheet.write(data_row, data_col + 1, row[1], data_format)

This sets the color for each column.

Answer

Martin Evans picture Martin Evans · Sep 20, 2016

There is nothing stopping you from setting the formats manually as follows. A context manager is used to automatically close the workbook afterwards.

import xlsxwriter

with xlsxwriter.Workbook('hello.xlsx') as workbook:
    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")

This would give you output looking as follows:

Alternating row colours


To apply this to a list of data, you could use the following approach. This also shows how it could be extended to use additional formats:

import xlsxwriter
from itertools import cycle

data = ["Row 1", "Row 2", "Row 3", "Row 4", "Row 5", "Row 6"]

with xlsxwriter.Workbook('hello.xlsx') as workbook:
    data_format1 = workbook.add_format({'bg_color': '#EEEEEE'})
    data_format2 = workbook.add_format({'bg_color': '#DDDDDD'})
    data_format3 = workbook.add_format({'bg_color': '#CCCCCC'})
    formats = cycle([data_format1, data_format2, data_format3])

    worksheet = workbook.add_worksheet()

    for row, value in enumerate(data):
        data_format = next(formats)

        worksheet.set_row(row, cell_format=data_format)
        worksheet.write(row, 0, value)

Second version