#-*- encoding:utf-8 -*-
import json
import xlrd
def readExcel():
# 打开excel表单
filename = u'学生信息.xlsx'
excel = xlrd.open_workbook(filename)
# 得到第一张表单
sheet1 = excel.sheets()[0]
#找到有几列几列
nrows = sheet1.nrows #行数
ncols = sheet1.ncols #列数
totalArray=[]
title=[]
# 标题
for i in range(0,ncols):
title.append(sheet1.cell(0,i).value);
#数据
for rowindex in range(1,nrows):
dic={}
for colindex in range(0,ncols):
s=sheet1.cell(rowindex,colindex).value
dic[title[colindex]]=s
totalArray.append(dic);
return json.dumps(totalArray,ensure_ascii=False)
import json
import xlrd
def readExcel():
# 打开excel表单
filename = u'学生信息.xlsx'
excel = xlrd.open_workbook(filename)
# 得到第一张表单
sheet1 = excel.sheets()[0]
#找到有几列几列
nrows = sheet1.nrows #行数
ncols = sheet1.ncols #列数
totalArray=[]
title=[]
# 标题
for i in range(0,ncols):
title.append(sheet1.cell(0,i).value);
#数据
for rowindex in range(1,nrows):
dic={}
for colindex in range(0,ncols):
s=sheet1.cell(rowindex,colindex).value
dic[title[colindex]]=s
totalArray.append(dic);
return json.dumps(totalArray,ensure_ascii=False)
print readExcel();
学生信息.xlsx
<
姓名 | 学号 | 性别 | 年龄 |
孙悟空 | 10000 | 男 | 21 |
猪八戒 | 10001 | 女 | 20 |
沙和尚 | 10002 | 男 | 21 |
唐僧 | 1003 | 女 | 19 |
结果:
G:\Code\python>python read_excel.py
[{"年龄": 21.0, "性别": "男", "姓名": "孙悟空", "学号": 10000.0}, {"年龄": 20.0, "性别": "女", "姓名": "猪八戒", "学号": 10001.0}, {"年龄": 21.0, "性别": "男", "姓名": "沙和尚", "学号": 10002.0}, {"年龄": 19.0, "性别": "女", "姓名": "唐僧", "学号": 1003.0}]