2013-06-12 55 views
1

如果我有幾個數組,我想用Python寫入一個excel文件,那麼最好的方法是什麼?我嘗試了幾種方法,並不能弄明白....這是林很新的這如何將幾個數組寫入excel文件?

import xlwt 
from tempfile import TemporaryFile 
book = xlwt.Workbook() 
sheet1 = book.add_sheet('sheet1') 


a=[1,2,3,4,5] 
b=[6,7,8,9,10] 
c=[2,3,4,5,6] 

data = [a,b,c] 

for i,e in enumerate(data): 
    sheet1.write(i,1,e) 

name = "this.xls" 
book.save(name) 
book.save(TemporaryFile()) 
+2

你的數據有兩個維度,這表明你需要一個嵌套循環。對於行,枚舉(數據)中的數組:col,枚舉(數組)中的值:sheet.write(row,col,value)'或類似的東西。 –

回答

3

按照史蒂芬Rumbalski建議的一個辦法,我想......一個例子,

import xlwt 
from tempfile import TemporaryFile 
book = xlwt.Workbook() 
sheet1 = book.add_sheet('sheet1') 


a=[1,2,3,4,5] 
b=[6,7,8,9,10] 
c=[2,3,4,5,6] 

data = [a,b,c] 

for row, array in enumerate(data): 
    for col, value in enumerate(array): 
     sheet1.write(row, col, value): 

name = "this.xls" 
book.save(name) 
book.save(TemporaryFile()) 
0

另一種可供選擇的方法是將數組寫爲分隔文本文件。 Excel可以輕鬆讀取這些文件(只需打開它們就像是Excel工作表一樣,您將獲得導入對話框)。

下面是這樣做的代碼 -

path='foo.txt' 

a=[1,2,3,4,5] 
b=[6,7,8,9,10] 
c=[2,3,4,5,6] 

with open(path,'w') as table: 
    for row in zip(a,b,c): 
     for cell in row: 
      table.write(str(cell) + '\t') 
     table.write('\n') 

在這種情況下,陣列被縱向書寫,和細胞由製表符分隔(Excel處理冗餘標籤沒有問題)。