You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON列表转Dataframe导出多Excel工作表的代码问题求助

问题排查:将JSON列表转为多工作表Excel文件

待转换的JSON数据

[
  [],
  [
    {
      "Tax": "69.767442",
      "Details": {
        "Attributes": "dejje",
        "Name": "Plate",
        "additionalAttributes6": "",
        "Nuber": "",
        "additionalAttributes8": "",
        "summaryDescription": "",
        "Discount": "",
        "Groups": "",
        "taxInclusive": "",
        "additionalAttributes7": ""
      }
    }
  ],
  [
    {
      "Tax": "69.767442",
      "Details": {
        "Attributes": "",
        "Name": "",
        "additionalAttributes6": "",
        "Nuber": "",
        "additionalAttributes8": "",
        "summaryDescription": "",
        "Discount": "",
        "Groups": "",
        "taxInclusive": "10.19",
        "additionalAttributes7": ""
      }
    }
  ]
]

原尝试代码

with open('data.json') as file:

    data = json.load(file)
    arg_mode = 'a' if 'out.xlsx' in os.getcwd() else 'w' # line added
    df = []
    index = 0
    for value in data:
        df[index] = pd.DataFrame(json_normalize(value, max_level=1))
        with pd.ExcelWriter('out.xlsx') as writer:
          df[index].to_excel(writer,mode=arg_mode,index=False,sheet_name=df[index],engine="openpyxl")
        index = index + 1

代码存在的问题

  • 缺少必要的导入语句:代码中使用了json、os、pd(pandas)和json_normalize,但没有对应的import语句,运行会触发NameError。
  • 列表索引赋值错误:df是一个空列表,直接用df[index] = ...会触发IndexError,空列表没有对应索引的位置,应该用df.append(...)添加元素。
  • ExcelWriter的使用错误:每次循环都重新创建ExcelWriter并打开文件,会导致每次写入覆盖之前的工作表(即使使用mode='a',with块结束时文件会被关闭,重新打开的默认行为不符合预期)。正确做法是只创建一次ExcelWriter,在循环中逐个写入工作表。
  • 工作表名称错误:sheet_name=df[index]试图把DataFrame对象作为工作表名,会触发错误,工作表名必须是字符串,比如Sheet_{index+1}这类命名。
  • 文件存在判断逻辑错误:'out.xlsx' in os.getcwd()是检查文件名是否在路径字符串中,逻辑错误,应该用os.path.exists('out.xlsx')判断文件是否存在。
  • 空列表处理问题:原始数据第一个元素是空列表,转成DataFrame后为空表,写入时需明确是否保留或跳过。

修正后的代码

import json
import os
import pandas as pd
from pandas import json_normalize

# 读取JSON数据
with open('data.json') as file:
    data = json.load(file)

# 判断文件是否存在,确定写入模式
file_exists = os.path.exists('out.xlsx')
mode = 'a' if file_exists else 'w'

# 初始化ExcelWriter,仅创建一次
with pd.ExcelWriter(
    'out.xlsx', 
    mode=mode, 
    engine='openpyxl', 
    if_sheet_exists='replace' if file_exists else None
) as writer:
    for idx, value in enumerate(data):
        # 处理空列表:可选择写入空表或跳过
        if not value:
            sheet_name = f'Sheet_{idx+1}'
            pd.DataFrame().to_excel(writer, sheet_name=sheet_name, index=False)
            continue
        
        # 转换为扁平化DataFrame
        df = json_normalize(value, max_level=1)
        # 定义工作表名称
        sheet_name = f'Sheet_{idx+1}'
        # 写入工作表
        df.to_excel(writer, sheet_name=sheet_name, index=False)

说明

  1. 补充了所有必要的导入语句,避免运行报错。
  2. 修正了文件存在判断逻辑,使用os.path.exists替代错误的字符串包含判断。
  3. 将ExcelWriter放在循环外,确保一次打开文件完成所有工作表写入,避免覆盖问题。
  4. 使用enumerate简化索引处理,用字符串作为工作表名称,解决对象命名的错误。
  5. 增加了空列表的处理逻辑,可根据需求选择写入空表或直接跳过。
  6. 添加if_sheet_exists='replace'参数(文件存在时),避免重复工作表名冲突,也可改为'new'创建新表。

内容的提问来源于stack exchange,提问作者Codephree Coding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:07:05