You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python openpyxl将字典中的日期以正确格式写入Excel?

解决Excel写入日期显示为文本的问题

问题出在你用strftime()把datetime对象转成了字符串,Excel只会把字符串识别成文本格式。要让Excel正确识别为日期,得直接存入datetime对象,再设置单元格的日期显示格式。

修改步骤:

  1. 保留datetime对象,不要转字符串
    把代码中日期处理的部分去掉strftime("%d/%m/%Y"),直接用解析后的datetime对象:

    Declaration_dict = Excel_Dict(r"\\path_to_excel_file.xlsx")
    for row in Declaration_dict:
        if row['statut'] == 'OK':
            # 直接保留datetime对象,不转字符串
            line_declaration = (
                row['Cle_modifiee'], row['via'], row['Reference'],
                datetime.fromisoformat(row['Date']),  # 这里修改
                row['Detail'], row['NOM'], row['User'],
                row['Metier'], row['Equipe'], row['Libelle']
            )
            sheet_stock.append(line_declaration)
    
  2. 设置单元格的日期显示格式
    存入datetime对象后,需要给日期列设置格式,让Excel按日/月/年显示。假设日期在第4列(对应Excel的D列),可以用两种方式设置:

    # 方法1:设置整列格式(推荐,一次性生效)
    sheet_stock.column_dimensions['D'].number_format = 'DD/MM/YYYY'
    
    # 方法2:逐行设置(仅修改新增的行)
    # 在sheet_stock.append(line_declaration)之后添加:
    current_row = sheet_stock.max_row
    date_cell = sheet_stock.cell(row=current_row, column=4)
    date_cell.number_format = 'DD/MM/YYYY'
    

这样处理后,Excel会把单元格识别为日期类型,同时按你需要的格式显示,不会再是文本格式。

内容的提问来源于stack exchange,提问作者Samir ZAABLI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:55:19