处理excel
可使用xlrd模块,需要安装
https://pypi.org/project/xlrd/
文档可参考:
https://xlrd.readthedocs.io/en/latest/api.html
所有读取到的中文会处理为unicode编码
转换成json
可使用自带的json函数
json.dumps
注意各种可选参数:
ensure_ascii = False,可处理中文乱码问题,默认为True,此时保存到文件会变成unicode
sort_keys = True, indent = 4, separators = (',', ':'),可处理格式化,sort_keys排序,indent缩进,separators分隔
一个例子
import xlrd
import json
curDir= os.path.dirname(os.path.realpath(__file__))
excelName = os.path.join(curDir, 'Test.xlsx')
jsonData = {}
# 打开一个workbook
workBook = xlrd.open_workbook(excelName)
# 抓取所有sheet页的名称
workSheets = workBook.sheet_names()
for i, sheet in enumerate(workSheets):
# 解码为utf8 原本为unicode
jsonData['name%d' % (i)] = sheet.encode('utf-8')
# 格式化输出json字符串
jsonString = json.dumps(jsonData, sort_keys = True, indent = 4, separators = (',', ':'), ensure_ascii = False)
# 写入文件
fw = open(os.path.join(curDir, 'all.json'), 'w')
fw.write(jsonString)
fw.close()