繁体   English   中英

如何使用python从xlsx文件加载数据

[英]How to load data from an xlsx file using python

这是我的xlsx文件:

在此输入图像描述

我希望将这些数据更改为这样的字典

{
    0:{
       'a':1,
       'b':100,
       'c':2,
       'd':10
    },
    1:{
       'a':8,
       'b':480,
       'c':3,
       'd':14
    }
...
}

所以有人知道一个python lib来做这件事,并从第124行开始,第141行结束,

谢谢

假设你有这样的数据:

a,b,c,d
1,2,3,4
2,3,4,5
...

2014年的许多潜在答案之一是:

import pyexcel


r = pyexcel.SeriesReader("yourfile.xlsx")
# make a filter function
filter_func = lambda row_index: row_index < 124 or row_index > 141
# apply the filter on the reader
r.filter(pyexcel.filters.RowIndexFilter(filter_func))
# get the data
data = pyexcel.utils.to_records(r)
print data

现在数据是一个字典数组:

[{
   'a':1,
   'b':100,
   'c':2,
   'd':10
},
{
   'a':8,
   'b':480,
   'c':3,
   'd':14
}...
]

文档可以在这里阅读

使用xlrd的选项:

(1)你的xlsx文件看起来不是很大; 将其保存为xls。

(2)使用xlrd加上bolt-on beta-test模块xlsxrd (找到我的电子邮件地址并要求它); 该组合将无缝地从xls和xlsx文件中读取数据(相同的API;它检查文件内容以确定它是xls,xlsx还是冒名顶替者)。

在任何一种情况下,类似下面的(未经测试的)代码应该做你想要的:

from xlrd import open_workbook
from xlsxrd import open_workbook
# Choose one of the above

# These could be function args in real live code
column_map = {
    # The numbers are zero-relative column indexes
    'a': 1,
    'b': 2,
    'c': 4,
    'd': 6,
    }
first_row_index = 124 - 1
last_row_index = 141 - 1
file_path = 'your_file.xls'

# The action starts here
book = open_workbook(file_path)
sheet = book.sheet_by_index(0) # first worksheet
key0 = 0
result = {}
for row_index in xrange(first_row_index, last_row_index + 1):
    d = {}
    for key1, column_index in column_map.iteritems():
        d[key1] = sheet.cell_value(row_index, column_index)
    result[key0] = d
    key0 += 1

另一种选择是openpyxl 我一直想尝试一下,但还没有解决它,所以我不能说它有多好。

这是一个使用标准库的非常粗略的实现。

def xlsx(fname):
    import zipfile
    from xml.etree.ElementTree import iterparse
    z = zipfile.ZipFile(fname)
    strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
    rows = []
    row = {}
    value = ''
    for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
        if el.tag.endswith('}v'): # <v>84</v>
            value = el.text
        if el.tag.endswith('}c'): # <c r="A3" t="s"><v>84</v></c>
            if el.attrib.get('t') == 's':
                value = strings[int(value)]
            letter = el.attrib['r'] # AZ22
            while letter[-1].isdigit():
                letter = letter[:-1]
            row[letter] = value
        if el.tag.endswith('}row'):
            rows.append(row)
            row = {}
    return dict(enumerate(rows))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM