1. 程式人生 > >python將Excel資料匯出幷儲存在json檔案中

python將Excel資料匯出幷儲存在json檔案中

一:python3.6,安裝xlrd模組(windows 環境下easy_install-3.6.exe xlrd)

二:程式碼如下:

# -*- coding: utf-8 -*-
import xlrd
import json


def open_excel(file):
    """
    開啟execl檔案
    :param file: excel檔名字
    :return:
    """
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception as e:
        print("Error: " + str(e))


def parse_by_sheet_name(file, sheet_name):
    """
    獲取Excel資料
    :param file: Excel檔名稱
    :param sheet_name: sheet頁名稱
    :return: 該sheet頁的資料(陣列格式,每個成員是一個字典)
    """
    data = open_excel(file)
    table = data.sheet_by_name(sheet_name)
    nrows = table.nrows
    row_list = []

    for i in range(0, nrows):
        row_value = table.row_values(i)
        data_dict = dict()
		# 對應Excel的第一列資料和第二列資料
        data_dict["ErrCode"] = int(row_value[0])
        data_dict["ErrMsg"] = row_value[1]
        row_list.append(data_dict)

    return row_list


def write_to_json_file(data, file_name):
    """
    寫入json檔案
    :param data: json資料
    :param file_name: json檔名稱
    :return:
    """
    try:
        # 對中文編碼處理,使得生成的json檔案中中文能正常顯示,而不是以Unicode碼顯示
        final_json = json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
        with open(file_name, 'w') as fObj:
            fObj.write(final_json)

    except Exception as e:
        print("Error: " + str(e))


if __name__ == '__main__':
    excel_data = parse_by_sheet_name("test.xlsx", "Sheet1")
    print(excel_data)
    final_data = dict()
    final_data["version"] = int(1)
    final_data["contents"] = excel_data
    write_to_json_file(final_data, "test.json")

三:輸出

Excel文件:


生成的json檔案: