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

zjm*_*126 6 python xlsx

这是我的xlsx文件:

在此输入图像描述

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

{
    0:{
       'a':1,
       'b':100,
       'c':2,
       'd':10
    },
    1:{
       'a':8,
       'b':480,
       'c':3,
       'd':14
    }
...
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Joh*_*hin 1

xlrd的选项:

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

(2) 使用xlrd附加的 beta 测试模块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
Run Code Online (Sandbox Code Playgroud)