操作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')#調用函數,傳入參數