用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)

你可能感兴趣的:(Python,Solution)