2016-01-06 80 views
2

我使用xlwt與Python從某些東西獲取一些數據,並將其寫入xls文件,但我需要在不同範圍的單元格中獲取輸出。 我有這樣的代碼: -我如何獲得不同範圍的細胞值?

#Here's the code for that : 
    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 = "table.xls" 
    book.save(name) 
    book.save(TemporaryFile()) 

輸出( 「table.xls」):

#Output 
    * A B C D E 

    1 1 2 3 4 5 

    2 6 7 8 9 10 

    3 2 3 4 5 6 

但我想是這樣的:

# I want the values in different ranges of cells 

* A B C D E F G H I 

1 1  6  2 3 4 5 6 

2 2  7 

3 3  8 

4 4  9 

5 5  10 

誰能幫助我?感謝

+0

我看到你想要第一個和第二個列表作爲列和第三個列表作爲行...是否正確? –

+0

@鐵拳是的。 –

+0

@ Iron Fist ...我也需要你的幫助http://stackoverflow.com/questions/34676285/how-can-i-create-duplicate-sheets-from-sheet1-then-input-list-data-in -those-s –

回答

1

我認爲最簡單的方法之一是使用izip_longestitertools模塊,這種方式:

>>> a=[1,2,3,4,5] 
>>> b=[6,7,8,9,10] 
>>> c=[2,3,4,5,6] 
>>> c_ = [[x] for x in c] 
>>> c_ 
[[2], [3], [4], [5], [6]] 
>>> data = list(izip_longest(a,[],b,[],*c_, fillvalue='')) 
>>> for i in data: 
    l = [] 
    for j in i: 
     l.append(j) 
    print l 

[1, '', 6, '', 2, 3, 4, 5, 6] 
[2, '', 7, '', '', '', '', '', ''] 
[3, '', 8, '', '', '', '', '', ''] 
[4, '', 9, '', '', '', '', '', ''] 
[5, '', 10, '', '', '', '', '', ''] 

現在您可以輕鬆將其寫入到Excel文件:

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

我假設你正在使用Python2

+0

@JehanMazen ..我假設你可以使用'itertools'模塊,對嗎? –

+0

好的工作..謝謝@鐵拳 –

+0

@JehanMazen ..沒有pblm –