如何获得不同范围的单元格中的值? [英] How can i get values in different ranges of cells?

查看:64
本文介绍了如何获得不同范围的单元格中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将xlwt与Python结合使用,以从某物获取某些数据并将其写入xls文件中,但是我需要获取不同单元格范围内的输出. 我有这样的代码:-

I am using xlwt with Python to get some data from something and writing it in an xls file,but I need to get outputs in different ranges of cells. I have code like this:-

 #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()) 

Output("table.xls"):

Output("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

但是我想要这样的东西:

But I want something like this:

# 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

有人可以帮助我吗?谢谢

Can anyone help me? thanks

推荐答案

我认为最简单的解决方案之一就是使用

I believe one of the easiest solution is to use izip_longest from itertools module, this way:

>>> 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文件:

Now you can easily write it to your excel file:

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

我假设您正在使用Python2

I assumed you are using Python2

这篇关于如何获得不同范围的单元格中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆