C/C++教程

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')

  

这篇关于pandas openpyxl 设置Excel 列宽自适应的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!