[python]使用Pandas将Excel文件转换为JSON格式

在数据处理和分析过程中,经常需要将Excel文件转换为JSON格式,以便在Web应用程序中使用。本文介绍如何使用Python的Pandas库实现这一功能,并解释其中的关键函数。

代码示例

python 复制代码
import pandas as pd
import json

def excel_to_json(excel_file):
    # 读取Excel文件
    xls = pd.ExcelFile(excel_file)
    
    # 创建一个空字典存储每个Sheet的数据
    excel_data = {}
    
    # 遍历每个Sheet
    for sheet_name in xls.sheet_names:
        # 读取Sheet内容为DataFrame
        df = pd.read_excel(excel_file, sheet_name=sheet_name)
        
        # 将DataFrame转换为字典格式
        data_dict = df.to_dict(orient='records')
        
        # 将数据存入字典,以Sheet名为键
        excel_data[sheet_name] = data_dict
    
    # 将字典转换为JSON字符串
    json_data = json.dumps(excel_data, indent=4, ensure_ascii=False)
    
    return json_data


# 使用示例
excel_file_path = '表格数据.xlsx'
json_output = excel_to_json(excel_file_path)
print(json_output)

# 如果需要保存为文件,可以使用以下代码:
with open('output.json', 'w', encoding='utf-8') as f:
    f.write(json_output)

代码解析

导入必要的库:

import pandas as pd

import json

定义excel_to_json函数:

读取Excel文件并获取所有Sheet的名称。

创建一个空字典来存储每个Sheet的数据。

遍历每个Sheet,将其内容读取为DataFrame,并转换为字典格式。

将每个Sheet的数据存入字典中,以Sheet名为键。

最后,将字典转换为JSON字符串并返回。

关键函数解释:

df.to_dict(orient='records'):

这个函数将Pandas DataFrame转换为字典格式。参数orient='records'表示每一行数据将作为一个字典存储在列表中。例如:

python 复制代码
[{'列1': 值1, '列2': 值2}, {'列1': 值3, '列2': 值4}]

json.dumps(excel_data, indent=4, ensure_ascii=False):这个函数将Python字典转换为JSON字符串。参数indent=4用于美化输出,使JSON字符串更易读;ensure_ascii=False确保输出的JSON字符串中包含非ASCII字符(如中文)时不会被转义。

指定Excel文件路径并调用excel_to_json函数。

打印生成的JSON数据。

如果需要保存为文件,可以使用with open语句将JSON数据写入文件。

相关推荐
共享家95275 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Hgfdsaqwr6 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
一晌小贪欢6 小时前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模6 小时前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr7 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448917 小时前
export_onnx.py_0130
pytorch·python·深度学习
s1hiyu7 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_763472467 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
无垠的广袤7 小时前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:缺陷检测
linux·人工智能·python·opencv·开发板