2016-01-29 90 views
0

我有一個包含數據的文件像下面xlwt:寫多列

a,b,c,d 
e,f,g,h 
i,j,k,l 

我試圖在使用Python xlwt 4列寫這一個Excel文件。我想在Excel中做到這一點,因爲我需要在同一個文件中創建多個工作表。 有很多關於如何通過循環編寫2列的例子,但是我找不到寫多列的例子。任何機構能告訴我如何完成這項工作?

回答

2

以下應該做你在找什麼:

import xlwt 

data1 = [["a1", "b1", "c1", "d1"], ["e1", "f1", "g1", "h1"], ["i1", "j1", "k1", "l1"]] 
data2 = [["a2", "b2", "c2", "d2"], ["e2", "f2", "g2", "h2"], ["i2", "j2", "k2", "l2"]] 
data3 = [["a3", "b3", "c3", "d3"], ["e3", "f3", "g3", "h3"], ["i3", "j3", "k3", "l3"]] 

sheets = ["Sheet 1", "Sheet 2", "Sheet 3"] 

wb = xlwt.Workbook() 

for sheet, data in zip(sheets, [data1, data2, data3]): 
    ws = wb.add_sheet(sheet) 

    for row, row_value in enumerate(data): 
     for col, col_value in enumerate(row_value): 
      ws.write(row, col, col_value) 

wb.save('output.xls') 

這將會給你一個Excel文件看起來像:

Excel screenshot