python 版本:2.7
只是读取excel的话可以直接使用xlrd
1、excle to json
代码如下
# -*-coding:utf8 -*- import xlrd from collections import OrderedDict import json import codecs file_name=raw_input('请输入要转换的excle文件路径:') wb = xlrd.open_workbook(file_name) dict_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] dict_list.append(single) j = json.dumps(dict_list) with codecs.open(file_name[:-5]'.json',"w","utf-8") as f: f.write(j)
2、json to excle
代码如下
注意:标题会写在最后一行,主要针对字段不同的json数据。
import json import os from openpyxl import Workbook wb = Workbook() ws = wb.active cols = [] def json2excel(jsfile, excfile): # 读取json数据 a = 1 if os.path.exists(jsfile): with open(jsfile, 'r') as fp: while True: line = fp.readline() if not line: break jsdata = json.loads(line) for k in jsdata.keys(): if k not in cols: cols.append(k) rowdata = [] for col in cols: rowdata.append(jsdata.get(col)) print '正在写入的行数:'a ws.append(rowdata) # 写行 a += 1 ws.append(cols) # 标题 print('保存中') wb.save(excfile) # 保存 if __name__ == '__main__': import sys if len(sys.argv) == 3: jsfile = sys.argv[1] excfile = sys.argv[2] json2excel(jsfile, excfile) else: print("Usage: python writeExc.py xx.json xx.xlsx")
以上这篇使用python对excle和json互相转换的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。