【问题标题】:Format dates on an entire column with ExcelWriter and Openpyxl使用 ExcelWriter 和 Openpyxl 在整个列上格式化日期
【发布时间】:2022-12-31 21:46:44
【问题描述】:

我正在尝试将 pandas DataFrame 写入 Excel,日期格式为“YYYY-MM-DD”,省略时间。由于我需要写多张纸,并且我想使用一些高级格式打开(即设置列宽),我使用ExcelWriter对象和openpyxl作为引擎。

现在,我似乎无法弄清楚如何格式化我的日期列。

从...开始

import pandas as pd
df = pd.DataFrame({'string_col': ['abc', 'def', 'ghi']})
df['date_col'] = pd.date_range(start='2020-01-01', periods=3)
with pd.ExcelWriter('test.xlsx', engine='openpyxl') as writer:
    df.to_excel(writer, 'test', index=False)

这会将日期写为2020-01-01 00:00:00。出于某种原因我无法理解,添加datetime_format='YYYY-MM-DD'没有效果如果 openpyxl 是选定的引擎(如果 engine 未指定,则工作正常)。

所以我正在尝试解决这个问题:

with pd.ExcelWriter('test.xlsx', engine='openpyxl') as writer:
    df.to_excel(writer, 'test', index=False)
    writer.sheets['test'].column_dimensions['B'].width = 50
    writer.sheets['test'].column_dimensions['B'].number_format = 'YYYY-MM-DD'

列宽已正确应用,但数字格式未正确应用。另一方面,它确实可以将样式应用于单个单元格:writer.sheets['test']['B2'].number_format = 'YYYY-MM-DD'

但是我怎样才能将格式应用到整个列(我有数万个单元格要格式化)?我在 openpyxl 文档中找不到任何关于如何处理整个专栏的内容......

注意:我可以这样做:

for cell in writer.sheets['test']['B']:
    cell.number_format = 'YYYY-MM-DD'

但我的观点恰恰是为了避免迭代每个单独的单元格。

【问题讨论】:

    标签: python pandas date openpyxl


    【解决方案1】:

    您可以将日期视为一列字符串并将其切片以获取 'YYYY-MM-DD'

    import pandas as pd
    
    df = pd.DataFrame({'string_col': ['abc', 'def', 'ghi']})
    
    df['date_col'] = pd.date_range(start='2020-01-01', periods=3)
    df['date_col'] = df['date_col'].astype("str").str.slice(start=0, stop=10)
    
    with pd.ExcelWriter('test.xlsx', engine='openpyxl') as writer:
        df.to_excel(writer, 'test', index=False)
        writer.sheets['test'].column_dimensions['B'].width = 50
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2019-09-30
      • 1970-01-01
      • 2010-12-28
      相关资源
      最近更新 更多