转自:http://www.iplaypy.com/json/7104.html
一、在将Excel文件转换为JSON数据格式之前,我们需要准备的条件
- 这次代码中我们需要安装python 2.7.X版本
- 还需要安装xlrd模块方法如后: -- pip install xlrd
二、转换Excel为JSON文件的Python源代码
# www.iplaypy.com python
import xlrd
from collections import OrderedDict
import json
import codecs
wb = xlrd.open_workbook('file.xlsx')
convert_list = []
sh = wb.sheet_by_index(0)
title = sh.row_values(0)
for rownum in range(1, sh.nrows):
rowvalue = sh.row_values(rownum)
single = OrderedDict()
for colnum in range(0, len(rowvalue)):
print(title[colnum], rowvalue[colnum])
single[title[colnum]] = rowvalue[colnum]
convert_list.append(single)
j = json.dumps(convert_list)
with codecs.open('file.json',"w","utf-8") as f:
f.write(j)