其他分享
首页 > 其他分享> > pandas openpyxl 设置Excel 列宽自适应

pandas openpyxl 设置Excel 列宽自适应

作者:互联网

引入包
import pandas as pd
from openpyxl.utils import get_column_letter
from pandas import ExcelWriter
import numpy as np

  自适应函数

def to_excel_auto_column_weight(df: pd.DataFrame, writer: ExcelWriter, sheet_name):
    """DataFrame保存为excel并自动设置列宽"""
    df.to_excel(writer, sheet_name=sheet_name, index=False)
    #  计算表头的字符宽度
    column_widths = (
        df.columns.to_series().apply(lambda x: len(x.encode('gbk'))).values
    )
    #  计算每列的最大字符宽度
    max_widths = (
        df.astype(str).applymap(lambda x: len(x.encode('gbk'))).agg(max).values
    )
    # 计算整体最大宽度
    widths = np.max([column_widths, max_widths], axis=0)
    # 设置列宽
    worksheet = writer.sheets[sheet_name]
    for i, width in enumerate(widths, 1):
        # openpyxl引擎设置字符宽度时会缩水0.5左右个字符,所以干脆+2使左右都空出一个字宽。
        worksheet.column_dimensions[get_column_letter(i)].width = width + 2

  数据

df = pd.DataFrame({
    'Region': ['East', 'East', 'South', 'North', 'West', 'South', 'North', 'West', 'West', 'South', 'West', 'South'],
    'Item': ['Apple', 'Apple', 'Orange', 'Apple', 'Apple', 'Pear', 'Pear', 'Orange', 'Grape', 'Pear', 'Grape',
             'Orange'],
    'Volume': [9000, 5000, 9000, 2000, 9000, 7000, 9000, 1000, 1000, 10000, 6000, 3000],
    'Month': ['July', 'July', 'September', 'November', 'November', 'October', 'August', 'December', 'November', 'April',
              'January', 'MaysdfasdfljasjASDFLAJSDFJADSFASFLASDFJASDLFJADSFKADSJF ASFDFDDSFASDFASD']
})

  保存

with pd.ExcelWriter(r'/Users/kingggg/Documents/PycharmProjects/tools/others/test.xlsx') as writer:
    to_excel_auto_column_weight(df, writer, f'TEST')

  

标签:openpyxl,column,widths,writer,Excel,df,West,列宽,name
来源: https://www.cnblogs.com/shclbear/p/16698294.html