1.环境安装
pip install xlrd
2.代码
excel 文件放在.py文件目录下即可
import xlrd
import json
import sys
def excel2json(file_path, sheet, jsonName):
# 读取Excel文件的sheet1
sheet = xlrd.open_workbook(file_path).sheets()[sheet]
# 按行读取
rows = sheet.nrows
# 保存关键字
keys = []
# 保存结果
result = []
for i in range(rows):
if i == 0:
keys = sheet.row_values(i) # 保存关键字
else:
record = {}
cnt = 0
# 将Excel文件的数据存入字典中
for item in sheet.row_values(i):
record[keys[cnt]] = item
cnt += 1
# 将字典存入列表
result.append(record)
# 重定向并输出json文件
with open(jsonName, "w+") as outputFile:
print(json.dumps(result, indent=4))
sys.stdout = outputFile
if __name__ == '__main__':
file_path = "schedule-2023.xlsx"
sheet = 1
jsonName = 'schedule-2023.json'
excel2json(file_path, sheet, jsonName)
3.Excel输入文件
输出的json文件
[
{
"sch": "Jan/2023",
"req_fnl": "12/01/2022",
"req_pc_rev": "12/05/2022",
"pms_tc": "12/16/2022",
"pms_so": "12/30/2022",
"pms_rel": "01/31/2023"
},
...
...
...
]