用Python将excel文件导出成json

1、相关说明
此脚本可以 将excel各个sheet中的数据分别导出到不同的json文件中,以原excel文件名+sheet名进行命名
数据传入参数有:excelPath, jsonPath, fileName三个。
依赖的库有:xlrd、json、codecs,尤其 xlrd需要事先安装好

2、Python脚本及测试示例
/Users/nisj/PycharmProjects/BiDataProc/oldPythonBak/excel2json.py
# -*- coding=utf-8 -*-
import xlrd
import warnings
import sys
from collections import OrderedDict
import json
import codecs
reload(sys)
sys.setdefaultencoding('utf8')

warnings.filterwarnings("ignore")

def excel2json(excelPath, jsonPath, fileName):
    wb = xlrd.open_workbook('{excelPath}{fileName}.xls'.format(excelPath=excelPath, fileName=fileName))

    convert_list = []
    for sheetNo in range(0, len(wb.sheets())):
        sheetName = wb.sheet_by_index(sheetNo).name
        sh = wb.sheet_by_index(sheetNo)
        title = sh.row_values(0)

        for rownum in range(1, sh.nrows):
            rowvalue = sh.row_values(rownum)
            single = OrderedDict()
            for colnum in range(0, len(rowvalue)):
                single[title[colnum]] = rowvalue[colnum]
            convert_list.append(single)

        j = json.dumps(convert_list)

        with codecs.open('{jsonPath}{fileName}-{sheetName}.json'.format(jsonPath=jsonPath, fileName=fileName, sheetName=sheetName), "w", "utf-8") as f:
            f.write(j)

# Batch Test
excelPath = '/Users/nisj/Desktop/'
jsonPath = '/Users/nisj/Desktop/'
fileName = 'mysqlDataDownload'
excel2json(excelPath, jsonPath, fileName)

要将一个包含多个JSON文件文件夹转换Excel文件,你可以使用Python中的pandas库来处理JSON数据,并将其导出Excel文件。下面是一个示例代码: ```python import os import pandas as pd import json def convert_folder_to_excel(json_folder, excel_file): json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')] data = [] for json_file in json_files: with open(os.path.join(json_folder, json_file)) as f: json_data = json.load(f) data.append(json_data) df = pd.DataFrame(data) df.to_excel(excel_file, index=False) # 替换为你的JSON文件夹路径和要导出Excel文件路径 json_folder = 'path/to/your/json/folder' excel_file = 'path/to/your/excel/file.xlsx' convert_folder_to_excel(json_folder, excel_file) ``` 在这个示例中,`convert_folder_to_excel` 函数接受一个JSON文件夹路径和要导出Excel文件路径作为参数。它首先使用 `os.listdir` 函数列出文件夹中的所有文件,并筛选出以 `.json` 结尾的文件。然后,它逐个打开JSON文件,将其加载为Python字典,并将字典添加到一个列表中。接下来,它使用pandas库创建一个DataFrame对象,并将数据填充到DataFrame中。最后,它使用DataFrame的 `to_excel` 方法将数据导出Excel文件。 记得将代码中的 `'path/to/your/json/folder'` 替换为你实际的JSON文件夹路径,以及将 `'path/to/your/excel/file.xlsx'` 替换为你实际的要导出Excel文件路径。运行代码后,你将得到一个包含JSON数据的Excel文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值