利用python实现json转execl
要将JSON数据转换为Excel文件,可以使用Python的pandas
库,它提供了高效的数据处理能力。以下是详细的实现步骤:
步骤1:安装依赖库
1
| pip install pandas openpyxl
|
pandas
:用于数据处理和Excel文件操作
openpyxl
:作为Excel写入引擎(pandas依赖)
步骤2:实现代码
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import json import pandas as pd from pathlib import Path
def json_to_excel(input_path, output_path, sheet_name="Sheet1", encoding="utf-8"): """ 将JSON文件转换为Excel文件 参数: input_path: JSON文件路径(或JSON格式字符串) output_path: 输出的Excel文件路径 sheet_name: Excel工作表名称(默认"Sheet1") encoding: 文件编码(默认utf-8) """ if isinstance(input_path, str) and Path(input_path).exists(): with open(input_path, 'r', encoding=encoding) as f: data = json.load(f) else: data = json.loads(input_path) df = pd.json_normalize(data, sep="_") df.to_excel( output_path, sheet_name=sheet_name, index=False, engine="openpyxl" ) print(f"成功转换: {output_path}")
if __name__ == "__main__": json_to_excel( input_path="input.json", output_path="output.xlsx", sheet_name="Data" ) json_str = ''' [ {"id": 1, "name": "Alice", "scores": {"math": 90, "english": 85}}, {"id": 2, "name": "Bob", "scores": {"math": 78, "english": 92}} ] ''' json_to_excel( input_path=json_str, output_path="from_string.xlsx" )
|
关键功能说明
自动展平嵌套结构
使用pd.json_normalize()
处理嵌套JSON对象(如示例中的”scores”字段),通过sep
参数指定分隔符(例如scores_math
)。
支持多种输入类型
- 可直接传入JSON文件路径
- 可直接传入JSON格式字符串
保留原始数据结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| [ { "id": 1, "name": "Alice", "contact": { "email": "alice@example.com", "phone": "123-456" }, "hobbies": ["Reading", "Swimming"] }, { "id": 2, "name": "Bob", "contact": { "email": "bob@example.com", "phone": "789-012" }, "hobbies": ["Gaming"] } ]
|
生成Excel效果
注意事项
复杂嵌套处理
对于多层嵌套结构(如列表套字典),可能需要预处理JSON数据或多次调用json_normalize
。
大数据集优化
处理超大型JSON文件时:
- 分块读取JSON数据
- 使用
pd.concat()
合并DataFrame
- 考虑使用
xlsxwriter
引擎提升性能
特殊数据类型
Excel不支持的数据类型(如日期时间对象)建议先转换为字符串再写入。
此方案适用于大多数常见JSON结构,可通过调整json_normalize
参数适应个性化需求。