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

如何用Python3将含空单元格的Excel表格转为JSON对象数组?

Python3 实现Excel转指定格式JSON数组

依赖安装

首先需要安装处理Excel的库openpyxl,在命令行执行:

pip install openpyxl

完整实现代码

import openpyxl
import json

def excel_to_json(excel_file_path):
    # 加载Excel工作簿
    wb = openpyxl.load_workbook(excel_file_path)
    # 获取第一个工作表(如果目标表不是第一个,改成对应表名,比如wb['Sheet2'])
    sheet = wb.active

    result = []
    current_cart = None

    # 跳过表头,从第二行开始遍历(Excel行号从1开始)
    for row in sheet.iter_rows(min_row=2, values_only=True):
        cart_name, item = row
        # 遇到非空的CARTS列,新建购物车条目
        if cart_name is not None and cart_name.strip() != "":
            current_cart = {
                "CARTS": cart_name.strip(),
                "ITEMS": []
            }
            result.append(current_cart)
        # 当前有购物车且商品项非空时,添加到对应列表
        if current_cart is not None and item is not None and item.strip() != "":
            current_cart["ITEMS"].append(item.strip())
    
    # 生成带格式的JSON字符串
    return json.dumps(result, indent=4, ensure_ascii=False)

# 示例调用,替换为你的Excel文件路径
if __name__ == "__main__":
    json_output = excel_to_json("your_excel_file.xlsx")
    # 打印结果
    print(json_output)
    # 写入JSON文件
    with open("output.json", "w", encoding="utf-8") as f:
        f.write(json_output)

代码说明

  • Excel读取:openpyxl.load_workbook加载文件,wb.active获取当前活跃工作表,也可直接指定表名。
  • 行遍历逻辑:iter_rows(min_row=2, values_only=True)跳过表头,直接获取单元格的原始值。
  • 空单元格处理:通过判断字符串非空且不为空白,区分新购物车和同购物车的商品项,避免无效数据混入。
  • JSON生成:json.dumps的indent=4保证输出格式工整,ensure_ascii=False支持中文等非ASCII字符。

注意事项

  • 确保Excel的列名与示例一致(CARTS、ITEMS),若列名不同,需调整代码中对应的判断逻辑。
  • 运行前替换代码中的your_excel_file.xlsx为实际文件路径。

内容的提问来源于stack exchange,提问作者A LXD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:12:02