安装xlrd
1 2 |
准备数据集

代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# -*- coding: utf-8 -*- """ @Time: 2018/6/20 @Author: songhao @微信公众号: zeropython @File: demo.py """ import sys import xlrd import json # 1. 从Excel文件中读取出Book对象 # print type(data) # 输出:<class 'xlrd.book.Book'> # 2. 获取sheet页对象 # 2.1 通过sheet索引获取 sheet1 = data.sheet_by_index(0) # print sheet1 # 输出:<xlrd.sheet.Sheet object at 0x7efc10319ed0> # 2.2 通过sheet名称获取 sheet2 = data.sheet_by_name('Sheet1') # print sheet2 # 输出:<xlrd.sheet.Sheet object at 0x7efbfb72db10> # 3. 获取sheet页的行数和列数 nrows = sheet1.nrows ncols = sheet1.ncols # print nrows,ncols # 输出:62 5 # 说明表格有62行、5列 # 4. 获取第0行的值(是一个列表) row_data = sheet1.row_values(0) # print row_data # 输出:[u'year', u'GDP', u'first industry', u'second industry', u'third industry'] # 5. 获取第0列的值(是一个列表) col_data = sheet1.col_values(0) # print col_data # 输出:[u'year', 1952.0, 1953.0, 1954.0, 1955.0,...] # 6. 使用行列索引(从0开始)获取单元格的数据 cell_A1 = sheet1.cell(0,0) # print cell_A1 # print type(cell_A1) # print cell_A1.value # 输出: ''' text:u'year' <class 'xlrd.sheet.Cell'> year ''' # 7. 应用:将Excel文件中的数据转换成json数组 # 索引(即表头) idx = sheet1.row_values(0) # 最终的数据列表 data = [] # 从第1行开始遍历循环所有行,获取每行的数据 for i in range(1,nrows): row_data = sheet1.row_values(i) # 组建每一行数据的字典 row_data_dict = {} # 遍历行数据的每一项,赋值进行数据字典 for j in range(len(row_data)): item = row_data[j] row_data_dict[idx[j]] = item # 将行数据字典加入到data列表中 data.append(row_data_dict) print(json.dumps(data,indent = 4,ensure_ascii=False)) # ensure_ascii |
如果不加 ensure_ascii=False
则显示如下

这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False:


