xlsxwriter / openpyxl:excel显示正确的格式,但直到修改单元格才应用它

我遇到了xlsxwriter(也有openpyxl)和excel的问题。 直到我打开工作簿,单击该单元格,然后按Enter键才能使用列格式。 该列具有正确的格式,但不会显示此格式,直到刚刚列出的步骤出现。 我确信我的Excel有自动计算function。 而且,使用相同的代码行,一些列是格式良好的,另一些则不是。

wb = xlsxwriter.Workbook(filename) ws = wb.add_worksheet() numeric = wb.add_format() numeric.set_num_format(0x02) # also tried with 0x44 accounting, same results ... (get the request csv object) for item in (request): col=0 row +=1 for field in fields: if field: ws.write(row, col,item[field]) col += 1 if 'inventory' in item: if len(item['inventory']) > 0: ws.write(row, col,item['inventory'][0]['count'],numeric) ws.write(row, col+1,item['inventory'][0]['reorder_point'],numeric) ws.write(row, col+2,item['inventory'][0]['restock_level'],numeric) ws.set_column('Q2:Q'+str(row+1), 10, numeric) ws.set_column('R2:R'+str(row+1), 10, numeric) ws.set_column('T2:T'+str(row+1), 10, numeric) ws.set_column('U2:U'+str(row+1), 10, numeric) ws.set_column('V2:V'+str(row+1), 10, numeric) ws.set_column('AB2:AB'+str(row+1), 10, numeric) ws.set_column('AC2:AC'+str(row+1), 10, numeric) ws.set_column('AD2:AD'+str(row+1), 10, numeric) wb.close() 

在这个截断的代码中,列Q,U,V,AB,AC和AD不能正确显示,而列R和T却是这样。 由于我对xlsxwriter和openpyxl都有同样的问题,excel有问题吗? 我究竟做错了什么? 最后一个线索:如果我在Excel中更改列格式,除了列的重新计算(双重cliqued)的单元格外,它什么都不做。 感谢您的帮助。

XlsxWriter的set_column()方法的语法是:

 set_column(first_col, last_col, width, cell_format, options) 

而不是数字零索引first_col, last_col您可以使用Excel的A:D风格表示法:

 worksheet.set_column('E:E', 20) 

然而,在你的例子中,你正在使用一个2D范围,如:

 ws.set_column('Q2:Q5', 10, numeric) 

这是无效的。