导出到 Excel 时保留所有格式

问题描述 投票:0回答:1

我有数据框 df_brands,我想格式化这个 df 并导出到 Excel 文件,但我有一个问题

我有 df_brands:

enter image description here

然后我格式化这个 df:

enter image description here

之后我想将这个格式化的 df 保存在 Excel 文件中,但这很糟糕:

enter image description here

我想在导出到 Excel 文件时保留所有格式。我还想修复列的列宽

也许我可以通过其他方式导出?也许如图所示?但我想保存表格格式

python pandas export-to-excel pandas-styles
1个回答
0
投票

当您导出“样式数据框”(这是与简单数据框不同的对象)时,您将丢失一些“样式”。

要在最终的Excel文件中获得您想要的样式,有2种方法:

  • 使用“pandas styled dataframe”:速度很快,但某些样式不会导出到 Excel
  • 使用专用于 Excel 的库(例如“openpyxl”):通常速度较慢...特别是当您需要逐个单元格应用样式时
  1. 将 Excel 单元格中的值居中

给这个函数一个 df,你将得到一个样式化的 dfs,其中值居中。

import pandas as pd

def df_centerer(df):
    dfs = df.style.set_table_styles([dict(selector='th',
                                     props=[('text-align', 'center')])])
    dfs.set_properties(**{'text-align': 'center'})
    return dfs
  1. 调整列宽

我用 openpyxl 来做。

注意:您的屏幕截图来自 Jupyter。谁告诉你这不是 Jupyter 善意地为你调整列宽?

下面的函数中“ws”是一个工作表对象。 “num”表示我想要使用的列宽

from openpyxl.styles import Alignment

COLS_WIDTH = {1: ["ABCDEFGH", [20]*8],
              2: ["ABCDEF", [15] * 2 + [40] * 3 + [15]],
              3: ["ABC", [30] * 4]}

def ws_formatter(ws , num):
    # Adjust columns widths
    for idx, col in enumerate(COLS_WIDTH[num][0]):
        ws.column_dimensions[col].width = COLS_WIDTH[num][1][idx]
    
    # Set Autofilter on the whole table
    ws.auto_filter.ref = ws.dimensions
    
    # Freeze panes
    ws.freeze_panes = "B2"
© www.soinside.com 2019 - 2024. All rights reserved.