Skip to main content
 首页 » 编程设计

python之如何获取不同单元格范围内的值

2025年05月04日15txw1958

我正在使用 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 

谁能帮帮我?谢谢

请您参考如下方法:

我相信最简单的解决方案之一是使用 izip_longest来自 itertools 模块,这样:

>>> 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