Excel 转化成JSON

Excel 转化成JSON

python 复制代码
import pandas as pd
import json
import os

def excel_to_json(excel_path, sheet_name=0, orient='records', save_path=None):
    """
    将Excel文件转换为JSON格式并可选择保存到文件
    
    参数:
        excel_path: Excel文件路径
        sheet_name: 工作表名称或索引,默认为第一个工作表
        orient: JSON格式取向('records'、'split'、'index'等),默认为'records'
        save_path: JSON文件保存路径,如果为None则不保存文件
    
    返回:
        JSON字符串
    """
    # 读取Excel文件
    df = pd.read_excel(excel_path, sheet_name=sheet_name)
    
    # 处理NaN值,替换为None以确保正确转换为JSON的null
    df = df.where(df.notnull(), None)
    
    # 转换为JSON字符串
    json_str = df.to_json(orient=orient, force_ascii=False, indent=2)
    
    # 如果指定了保存路径,则保存到文件
    if save_path:
        # 确保目录存在
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        
        # 保存到文件
        with open(save_path, 'w', encoding='utf-8') as f:
            f.write(json_str)
        print(f"JSON文件已保存至: {save_path}")
    
    return json_str

# 使用示例
if __name__ == "__main__":
    # 转换Excel并保存为JSON文件
    json_output = excel_to_json(
        excel_path="data.xlsx",
        sheet_name="Sheet1",
        orient='records',
        save_path="output/data.json"  # 指定保存路径
    )
    
    # 打印部分JSON内容预览
    print("JSON内容预览:")
    print(json_output[:200] + "..." if len(json_output) > 200 else json_output)
相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
譕痕3 天前
JSONObject与JSONArray封装数据格式区别
java·json
A黄俊辉A3 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github