Python自适应调整Excel的列宽度

使用python调整列宽度的逻辑需要自己写,这里是参考参考文章中的内容,使用openpyxl打开文件后,将列宽度根据列的内容进行指定,使用max(列的内容宽度 + 2) * 1.2来指定列宽

示例程序

假设有一个测试.xlsx的文件,使用如下程序自适应的调整列宽度

py 复制代码
import openpyxl


def auto_resize_column(excel_path):
    """自适应列宽度"""
    wb = openpyxl.load_workbook(excel_path)
    worksheet = wb.active
    for col in worksheet.columns:
        max_length = 0
        column = col[0].column_letter  # Get the column name
        for cell in col:
            try:  # Necessary to avoid error on empty cells
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = (max_length + 2) * 1.2
        worksheet.column_dimensions[column].width = adjusted_width
    wb.save(excel_path)


def main():
    excel = auto_resize_column("测试.xlsx")


if __name__ == '__main__':
    main()

参考文章

相关推荐
微学AI2 小时前
内网穿透的应用-服务器日志出现异常怎么办?Python监控、钉钉告警与远程处理教程
服务器·python·钉钉
_Jimmy_11 小时前
Agent 溯源精度提升方案
人工智能·python·langchain
SamChan9012 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步201512 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
颜酱12 小时前
09 | 重构项目结构
人工智能·python·langchain
kisloy13 小时前
【爬虫入门第8讲】Python爬虫反爬入门
开发语言·爬虫·python
Sisphusssss14 小时前
香橙派5plus GPIO
linux·python·ubuntu
颜酱15 小时前
08 | 把维度值同步到 Elasticsearch(生成阶段)
人工智能·python·langchain
久久学姐15 小时前
基础转码学 AI:Java+Python 双语言入门,3 个月可落地实战项目
java·python·ai·转码·实战项目
ZHOU_WUYI15 小时前
4. light wam 模型loss计算过程
开发语言·人工智能·python