Pandas DataFrame导出Excel时Date PI列着色函数未生效问题问询
问题原因及解决方法
核心错误点
df.style.applymap()不会修改原DataFrame,而是返回独立的Styler样式对象,你当前代码未接收该返回值,定义的样式规则直接被丢弃,因此color函数不会被调用。- 后续导出时调用的是原始DataFrame的
to_excel()方法,导出内容完全不包含之前定义的样式配置。
修正方案
- 接收样式处理后的
Styler对象 - 使用
Styler对象的to_excel()方法导出带样式的Excel - 补充color函数的默认返回值,避免无匹配条件时返回None触发警告
修正后完整代码
from datetime import datetime import pandas as pd import os def generate_report_all(): update_company_perf_on_ships() # 原有业务逻辑保持不变 writer = pd.ExcelWriter('Report.xlsx', engine='xlsxwriter', date_format='yyyy-mm-dd', datetime_format='yyyy-mm-dd') df3['Last Inspection'] = pd.to_datetime(df3['Last Inspection'].astype('datetime64[ns]')) df3['Date PI'] = pd.to_datetime(df3['Date PI'].astype('datetime64[ns]')) df3['Date PII'] = pd.to_datetime(df3['Date PII'].astype('datetime64[ns]')) def color(val): if val < datetime.now(): return 'background-color: red' # 无匹配条件时返回空样式 return '' # 接收样式对象 styled_df = df3.style.applymap(color, subset=['Date PI']) # 用样式对象导出Excel styled_df.to_excel(writer, sheet_name='Report Paris', index=False) writer.save() os.system("open -a 'Microsoft Excel.app' 'Report.xlsx'")
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

