首页 > 解决方案 > 使用 Python xlrd 将 Excel 转换为 Json

问题描述

我正在努力使用 python xlrd 将一些 excel 数据转换为 json

假设我有两列: ID Note 1 blue 1 green 1 yellow 2 white 3 green 3 black

我需要通过基于 ID 对数据进行分组来在 json 中呈现结果:

{
    "ID": "1",
    "notes": [
        {
            "note": "blue",
            "note": "green",
            "note": "yellow"
        }
    ]
},
{
    "ID": "2",
    "notes": [
        {
            "note": "white",

        }
    ]
},
{
    "ID": "3",
    "notes": [
        {
            "note": "green",
            "note": "black"
        }
    ]
}

标签: pythonxlrdsimplejson

解决方案


import xlrd
from collections import OrderedDict
import simplejson as json

wb = xlrd.open_workbook(r'C:................\Desktop\a.xlsx')
sh = wb.sheet_by_index(0)

data_list = []

for rownum in range(1, sh.nrows):
    data = OrderedDict()


    row_values = sh.row_values(rownum)

    data['ID'] = row_values[0]
    data['Notes'] = row_values[1]

    ................................


        data_list.append(data)


j = json.dumps(data_list, indent = 4)

with open(r'C:....................json', 'w') as f:
    f.write(j)

推荐阅读