文件保存在本地D盘下面的wen文件夹,数据格式json文件,
数据案列:
{
"records": [
{
"CORP_ID": "22892c",
"CUST_QW_ID": "wmOaVBCg",
"CUSTOMER_NO": "5713",
"CREATE_TIME": "20240716",
"STATUS": "1"
}
]
}
相关代码如下:
import json
import os
from openpyxl import Workbook
# Define file paths文件及输出路径
json_file_path = r'D:\wen\wei073110.json'
excel_file_path = r'D:\\wen\wei073110.xlsx'
# Function to load JSON data 数据导入及json格式校验
def load_json(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print("File not found. Please check the path.")
exit(1)
except json.JSONDecodeError as e:
print(f"JSON decode error: {e.msg} at line: {e.lineno}, col: {e.colno}")
exit(1)
# Function to create Excel workbook and add data 设置excel表头
def create_excel(data, file_path):
wb = Workbook()
ws = wb.active
# Define header
header = [
"账户", "客信号", "代码", "日期", "状态"
]
ws.append(header)
# Populate data 获取数据
for row in data.get('records', []):
ws.append([
row.get('CORP_ID', ''),
row.get('CUST_QW_ID', ''),
row.get('CUSTOMER_NO', ''),
row.get('CREATE_TIME', ''),
row.get('STATUS', '')
])
# Save Excel file 保存数据
try:
wb.save(file_path)
print("Excel file has been saved successfully.")
except IOError:
print("Unable to save the Excel file. Please check the path and permissions.")
exit(1)
# Main execution 开始执行
if __name__ == "__main__":
json_data = load_json(json_file_path)
if 'records' not in json_data:
print("No 'records' key found in JSON data.")
exit(1)
create_excel(json_data, excel_file_path)