如何使用 xlwt 从第二行开始写?

How to start to write from second line with xlwt?

我想要这样的回复

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

当前回复为:

20    50000   10   40000  90000
21    31000   2000 41000  74000    

这里我认为 col1col2 .. 正在被覆盖我该如何解决这个问题?我如何处理这里的 row_num 以便列值不会替换列名?

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)

只需在enumerate(iterable, start=0)函数中指定start参数即可:

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

同样,range(start, stop[, step]) 也支持在必要时从自定义索引开始:

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