python3用xlrd模块将本地excel转换为json
表格为行列颠倒形式:
#!/usr/bin/env python
# coding=utf-8
# 本地excel转换为json
import json
import xlrd
file = "product.xlsx"
data = xlrd.open_workbook(file)
# 第二个sheet表是路南东
table = data.sheets()[1]
# 行数
nrows = table.nrows
# 列数
ncols = table.ncols
# 这个就是每个字典的key值
keys = ['id','name']
# 偶数行值even循环,获取id
even_list = []
for j in range(0,nrows,2):
# 偶数行的值
even=table.row_values(j)
even_list += even
# 奇数行值odd循环,获取name
odd_list = []
for i in range(1,nrows,2):
# 奇数行的值
odd_value = table.row_values(i)
odd_list += odd_value
# 列表嵌套,存储两个列表,一个是id需要的值,一个是name需要的值[[id的值],[name的值]]
result_list = []
result_list.append(even_list)
result_list.append(odd_list)
# 最后结果,列表里面嵌套字典[{},{}]
r = []
for i in range(len(even_list)):
# 存储每一组数据的字典
s = {}
print("写入第%s个数据"%(i+1))
for x in range(len(keys)):
s[keys[x]] = result_list[x][i]
r.append(s)
print("完毕。")
returnJson = json.dumps(r,ensure_ascii=False)
with open("路南东.json",'w',encoding='utf-8')as f:
f.write(returnJson)
结果形式:
[{"id": "shadow421-2437", "name": ""},{"id": "shadow487-2830", "name": "15119"}]