Search code examples
pythonlistxlwt

How to start to write from second line with xlwt?


I want response like this

col1  col2   col3  col4  col5
20    50000   10   40000  90000
21    31000   2000 41000  74000

The current response is:

20    50000   10   40000  90000
21    31000   2000 41000  74000    

Here I think col1, col2 .. are being overwritten how can i solve this ? How can I handle row_num here so that the column values will not replace column names ?

wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('datas', cell_overwrite_ok=True)
font_style = xlwt.XFStyle()
font_style.font.bold = True

columns = ['col1', 'col2', 'col3', 'col4', 'col5']
rom_num=0
for col_num in range(len(columns)):
    ws.write(row_num, col_num, columns[col_num], font_style)

font_style = xlwt.XFStyle()
rows = [20, Decimal('50000.00'), Decimal('10.00'), Decimal('40000.00'), Decimal('90000.00'), 21, Decimal('31000.00'), Decimal('2000.00'), Decimal('41000.00'), Decimal('74000.00')]

for i,e in enumerate(rows):
    row_num += 1
    ws.write(int(i/5),int(i)%5, e)

Solution

  • Simply specify the start parameter in the enumerate(iterable, start=0) function:

    for i,e in enumerate(rows, start=1):
        row_num += 1
        ws.write(int(i/5),int(i)%5, e)
    

    Similarly the range(start, stop[, step]) also supports starting on a custom index if necessary:

    columns = ['col1', 'col2', 'col3', 'col4', 'col5']
    rom_num=0
    for col_num in range(1, len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style