Python excel转json

环境

  • Python 3.6.9

  • excel2json (1.0.1)

  • excel2json-3 (0.1.6)

  • openpyxl (3.0.10)

  • xlrd (2.0.1)

开始

  • 安装扩展
1
$ pip3 install excel2json excel2json-3 xlrd==1.2.0 openpyxl
  • 创建 excel_to_json.py,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#  -*- coding: utf-8 -*-

import json
import openpyxl
import excel2json

def main(orgin_path):
"""
excel转json,提取出excel文件的内容
:param orgin_path: 原始excel的路径
:return: 提取出来的json列表,每个sheet对应一个json文件
"""
# 加载excel
workbook = openpyxl.load_workbook(orgin_path)
# 所有sheet的名字
sheet_list = workbook.sheetnames
# excel转json
excel2json.convert_from_file(orgin_path)
# 对中文内容做处理
json_list = [];
for sheet in sheet_list:
with open(sheet+'.json', 'r') as file_obj:
content = file_obj.read()
with open(sheet+'.json', 'w') as file_obj:
file_obj.write(json.dumps(json.loads(content), ensure_ascii=False))
json_list.append(sheet+'.json')
return json_list

main('origin.xlsx');
  • 执行
1
$ python3 excel_to_json.py
-------------本文结束感谢您的阅读-------------
0%