编辑代码

import pandas as pd
import numpy as np
from openpyxl import Workbook

# 生成单月温度数据
def generate_month_data(year, month, prev_temp=None):
    days = pd.Timestamp(year, month, 1).days_in_month
    if month == 2 and year == 2025: days = 14  # 2月特殊处理
    dates = pd.date_range(f"{year}-{month}-01", periods=days*24, freq='H')
    temp = []
    if prev_temp is None:
        first_temp = 2 + np.random.rand()*6  # 首温度2-8℃
    else:
        first_temp = prev_temp + np.random.rand()*0.2 - 0.1  # 衔接前一月温度
    temp.append(round(first_temp, 2))
    for i in range(1, len(dates)):
        next_temp = temp[-1] + np.random.rand()*0.2 - 0.1
        temp.append(round(next_temp, 2))
    return dates, temp

# 创建Excel文件
wb = Workbook()
prev_temp = None

# 生成4个月数据
for year, month in [(2024, 11), (2024, 12), (2025, 1), (2025, 2)]:
    sheet_name = f"{year}{month}月"
    dates, temp = generate_month_data(year, month, prev_temp)
    if sheet_name == "2024年11月":
        ws = wb.active
        ws.title = sheet_name
    else:
        ws = wb.create_sheet(title=sheet_name)
    ws.append(["日期", "时间", "温度(℃)"])
    for d, t in zip(dates, temp):
        ws.append([d.date(), d.time(), t])
    prev_temp = temp[-1]

wb.save("2024-2025温度记录表.xlsx")