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')#调用函数,传入参数
 



原文地址:https://www.cnblogs.com/ttj57/p/13590691.html