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

StyleFrame多Sheet格式化异常:首Sheet正常后续Sheet样式错乱

问题解决:StyleFrame多Sheet格式错乱修复

问题根源分析

你遇到的格式颠倒问题,核心原因是每次循环用mode='a'追加写入Excel时,StyleFrame与pandas的ExcelWriter追加模式存在样式兼容问题,加上代码中重复实例化StyleFrame的冗余操作,导致后续Sheet的样式继承逻辑混乱。

修复步骤

1. 移除冗余的StyleFrame实例化

原代码中连续两次创建StyleFrame实例属于冗余操作,直接一步初始化带默认样式的实例即可:

# 删掉这行无效代码:sf = StyleFrame(df)
default_style = Styler(font_size=10, horizontal_alignment='left', wrap_text=False)
sf = StyleFrame(df, styler_obj=default_style)

2. 统一创建ExcelWriter,循环写入所有Sheet

把pd.ExcelWriter的创建移到循环外面,避免每次追加写入时的样式冲突,确保所有Sheet的样式基于同一个Writer上下文正确渲染:

# 将ExcelWriter初始化移至循环外部
with pd.ExcelWriter(excel_file, mode='w') as writer:
    for app in uniq_apps:
        # ... 原有的数据收集、处理逻辑保持不变 ...
        
        # 生成DataFrame后创建StyleFrame并设置样式
        default_style = Styler(font_size=10, horizontal_alignment='left', wrap_text=False)
        sf = StyleFrame(df, styler_obj=default_style)
        
        header_style = Styler(bold=True, font_size=14, horizontal_alignment='center')
        sf.apply_headers_style(styler_obj=header_style)
        
        sf.apply_style_by_indexes(
            sf[sf['SrcValue'] != sf['TgtValue']], 
            styler_obj=Styler(bg_color='yellow', font_size=10, horizontal_alignment='left', bold=True)
        )
        
        # 设置列宽与行高
        sf.set_column_width(columns=['AppInst','Platform','SrcEnv','TgtEnv'], width=15)
        sf.set_column_width(columns=['SrcRelType','SrcVersion','TgtRelType','TgtVersion'], width=25)
        sf.set_column_width(columns=['Param'], width=65)
        sf.set_column_width(columns=['SrcValue','TgtValue'], width=80)
        sf.set_row_height(rows=sf.row_indexes, height=15)
        
        # 写入当前Sheet
        sf.to_excel(writer, sheet_name=app, freeze_panes=(1,0), index=False)
        logger.info(f'Comparison written to output file for {app}')

3. 确保样式属性明确覆盖

在apply_style_by_indexes中明确指定所有需要的样式属性(比如horizontal_alignment='left'),防止StyleFrame默认继承意外的样式值。

修复后效果

所有Sheet将统一呈现预期样式:

  • 表头居中、加粗、字号14
  • 普通内容左对齐、字号10
  • SrcValue与TgtValue不一致的行黄底、左对齐、加粗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:02:43