使用Python的openpyxl库将Excel转换为指定格式JSON(含datetime)
将Excel数据转换为指定Python结构的实现方案
首先说明:你给出的预期输出并非标准JSON格式,而是包含自定义类实例的Python原生数据结构,以下是实现步骤:
1. 定义Measurement类
先创建对应的数据类,用来封装每个测量项的信息:
from datetime import datetime class Measurement: def __init__(self, calculated_date: datetime, X1: float, X2: float): self.calculated_date = calculated_date self.X1 = X1 self.X2 = X2 # 可选:添加该方法让打印结果更贴合预期格式 def __repr__(self): return f"Measurement(calculated_date={repr(self.calculated_date)}, X1={self.X1}, X2={self.X2})"
2. 读取Excel数据
使用pandas库读取Excel文件,先安装依赖:
pip install pandas openpyxl
然后读取数据(假设Excel列名包含calculated_date、A_X1、A_X2、B_X1、B_X2、C_X1、C_X2):
import pandas as pd # 替换为你的Excel文件路径 df = pd.read_excel("your_excel_file.xlsx", sheet_name="Sheet1")
3. 转换为目标结构
遍历Excel的每一行,构建对应的字典并加入列表:
file_name = [] for _, row in df.iterrows(): # 读取当前行的日期时间(pandas会自动解析为datetime类型) current_dt = row["calculated_date"] # 构建包含三个Measurement实例的字典 current_item = { "A": Measurement(current_dt, row["A_X1"], row["A_X2"]), "B": Measurement(current_dt, row["B_X1"], row["B_X2"]), "C": Measurement(current_dt, row["C_X1"], row["C_X2"]) } file_name.append(current_item)
可选:转成标准JSON格式
如果确实需要标准JSON(不支持自定义类,需转成字典结构),可以修改转换逻辑:
import json file_name_json = [] for _, row in df.iterrows(): # 将datetime转为JSON可序列化的字符串 dt_str = row["calculated_date"].strftime("%Y-%m-%d %H:%M:%S") current_item = { "A": { "calculated_date": dt_str, "X1": row["A_X1"], "X2": row["A_X2"] }, "B": { "calculated_date": dt_str, "X1": row["B_X1"], "X2": row["B_X2"] }, "C": { "calculated_date": dt_str, "X1": row["C_X1"], "X2": row["C_X2"] } } file_name_json.append(current_item) # 保存为JSON文件 with open("output.json", "w", encoding="utf-8") as f: json.dump(file_name_json, f, indent=4)
内容的提问来源于stack exchange,提问作者SAHAR GOHARSHENASAN
相关产品推荐
相关产品推荐

