天天看點

python excel轉json、json轉excel詳解

操作json檔案需要用到python内置庫json,操作excel檔案需要用到第三方庫openpyxl
import json#導入json庫
import openpyxl      
from openpyxl import Workbook

      
#excel轉json
def excel_to_json(excel_file,json_file):
    wb=openpyxl.load_workbook(excel_file)#讀取excel檔案
    excel_data={}#定義字典excel_data存儲每個表的資料{表名:資料}
    for sheet in wb.sheetnames:
        result = []  # 定義清單result存儲所有讀取資料
        for rows in wb[sheet]:#擷取表的每一行資料
            tmp=[]#定義清單tmp存儲每一行的資料
            for cell in rows:#周遊一行每個單元格的資料
                tmp.append(cell.value)
            result.append(tmp)
        excel_data[sheet]=result
    #覆寫寫入json檔案
    with open(json_file, mode=\'w\', encoding=\'utf-8\') as jf:
        json.dump(excel_data, jf, indent=2, sort_keys=True, ensure_ascii=False)

excel_to_json(r\'./test.xlsx\',r\'./test,json\')#調用函數,傳入參數

#json轉excel
def json_to_excel(json_file,excel_file):
    #讀取json檔案資料
    with open(json_file, mode=\'r\', encoding=\'utf-8\') as jf:
        json_data= json.load(jf)
    k = json_data.keys()
    wb = Workbook()#建立excel檔案
    for sheet_name in k:
        try:
            wb.remove(sheet_name)  # 如表已存在則移除工作表
        except:
            pass
        wb.create_sheet(sheet_name, 0)  # 建立表
        ws = wb[sheet_name]  # 操作指定表
        sheet_data = json_data[sheet_name]  # 擷取表要寫入的資料
        for t in range(1, len(sheet_data) + 1):  # 周遊要寫入的行數
            i = 65  # ASCII碼\'65\'表示\'A\'
            for j in range(1, len(sheet_data[t - 1]) + 1):  # 周遊每行要寫入的數量
                ws[\'%s%d\' % (chr(i), t)] = sheet_data[t - 1][j - 1]
                i += 1
    wb.save(excel_file)

json_to_excel(r\'./test,json\',r\'./test.xlsx\')#調用函數,傳入參數