python 把EXCEL读取为dict

来源:互联网 发布:windows 2008ntp服务器 编辑:程序博客网 时间:2024/05/20 03:43

场景需求:

有一张excel表,表名为test.xlsx。格式如下
nam age jhon 18 hack 19 james

希望读成对应的json对象:

[{u’age’: 18.0, u’name’: u’john’}, {u’age’: 19.0, u’name’: u’hack’}, {u’age’: u”, u’name’: u’james’}]

#!/usr/bin/env ython# encoding:utf-8from xlrd import open_workbookfrom itertools import izip_longestdef main():    xlsfilename = 'test.xlsx'    book = open_workbook(xlsfilename, formatting_info=False)    cursheet = book.sheet_by_index(0)    map_result = list()    for row in range(cursheet.nrows):        if row == 0:            colum_list = [cursheet.cell(0, col).value for col in range(cursheet.ncols)]        else:            content = [cursheet.cell(row, col).value for col in range(cursheet.ncols)]            content_map = map(lambda x: x.strip() if isinstance(x, basestring) else x, content)            map_result.append(dict(izip_longest(colum_list, content_map)))    print map_resultif __name__ == '__main__':    main()

关键点:要把第一行的内容全部读取出来,作为key,把其他行的内容读取出来作为value

原创粉丝点击