Python调整EXCEL内容高度

背景介绍

有时在打印EXCEL时,单元格内容较多,需多行显示,类似这样:

在打印时,需保证单元格内的内容全部可见。需手动调整每一行高度,如果数据行很多,也是不少的工作量。

实现思路

1.利用程序遍历EXCEL中的每个Sheet,遍历每行。

2.定位该行文字最多那个单元格。

3.计算文字最多的单元格高度,单元格宽度,文字大小、换行数、预留边距计算出该行高度。

4.修改此行高度为第3步计算出的高度,使得该行所有文本可见。

实现步骤

1.安装Python操作EXCEL的库

bash 复制代码
pip install openpyxl

2.编写代码

以下代码会将代码所在文件夹下的EXCEL进行读取,并处理行高度。

注意:代码会修改原文件,操作前请备份原文件。

python 复制代码
#pip install openpyxl


import os
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Alignment

def calculate_row_height(cell, column_width, padding=5):
    """
    计算单元格内容所需的行高度
    :param cell: 单元格对象
    :param column_width: 列宽(以字符数为单位)
    :param padding: 上下留白距离(磅)
    :return: 计算后的行高度(磅)
    """
    if cell.value is None:
        return None
    
    # 获取单元格字体信息
    font = cell.font
    font_size = font.size if font.size else 11
    
    # 获取单元格内容
    text = str(cell.value)
    
    # 计算显式换行符的行数
    explicit_lines = text.count('\n') + 1
    
    # 考虑列宽计算自动换行
    if column_width > 0:
        # 计算文本总字符数(中文按2个字符计算,因为中文更宽)
        total_chars = 0
        for char in text:
            if '\u4e00' <= char <= '\u9fff':  # 中文字符范围
                total_chars += 3
            elif char == '\n':
                continue
            else:
                total_chars += 1
        
        # 根据列宽和字体大小计算每行可容纳的字符数
        # 字体越大,每行可容纳的字符数越少
        font_ratio = 11 / font_size
        chars_per_line = column_width * font_ratio
        
        if chars_per_line > 0 and total_chars > 0:
            # 计算自动换行所需的行数
            auto_wrap_lines = max(1, int((total_chars + chars_per_line - 1) / chars_per_line))
            # 取显式换行和自动换行的较大值
            total_lines = max(explicit_lines, auto_wrap_lines)
        else:
            total_lines = explicit_lines
    else:
        total_lines = explicit_lines
    
    # 行高计算:字体大小 * 行数 + 上下留白
    base_height = font_size * 1.4
    row_height = base_height * total_lines + padding * 2
    
    return row_height

def adjust_excel_row_heights(file_path):
    """
    调整Excel文件中所有行的高度
    :param file_path: Excel文件路径
    """
    try:
        # 加载工作簿
        wb = load_workbook(file_path)
        
        for sheet_name in wb.sheetnames:
            ws = wb[sheet_name]
            print(f"正在处理工作表: {sheet_name}")
            
            # 获取最大行和最大列
            max_row = ws.max_row
            max_col = ws.max_column
            
            if max_row < 2:
                print("  工作表数据不足,跳过")
                continue
            
            # 从第2行开始遍历
            for row in range(2, max_row + 1):
                max_height = None
                
                # 遍历当前行的所有单元格
                for col in range(1, max_col + 1):
                    cell = ws.cell(row=row, column=col)
                    cell.alignment = Alignment(wrap_text=True, vertical='center', horizontal='center')
                    col_letter = get_column_letter(col)
                    column_width = ws.column_dimensions[col_letter].width
                    if column_width is None or column_width == 0:
                        column_width = 8.43
                    height = calculate_row_height(cell, column_width)
                    
                    if height is not None:
                        if max_height is None or height > max_height:
                            max_height = height
                
                # 如果计算出了高度,则设置行高
                if max_height is not None:
                    ws.row_dimensions[row].height = max_height
                    # 打印进度信息(每10行打印一次)
                    if (row - 1) % 10 == 0:
                        print(f"  已处理第 {row} 行,行高设置为 {max_height:.1f} 磅")
        
        # 保存文件
        wb.save(file_path)
        print(f"文件 {file_path} 已成功保存!")
        
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {str(e)}")

if __name__ == "__main__":
    # 获取当前目录下所有xlsx文件(排除临时文件)
    xlsx_files = [f for f in os.listdir('.') if f.endswith('.xlsx') and not f.startswith('~$')]
    
    if not xlsx_files:
        print("当前目录下没有找到Excel文件")
    else:
        print(f"找到 {len(xlsx_files)} 个Excel文件")
        for file in xlsx_files:
            print(f"\n处理文件: {file}")
            adjust_excel_row_heights(file)
        print("\n处理完成!")

调整后结果

虽然使用场景不多,不过工作中遇到了,在此记录一下。

相关推荐
anlog1 小时前
excel计算今天的日期加上n天后的日期
excel·日期计算·今天日期
chatexcel13 小时前
AI知识库教程:基于ChatExcel实现规则文档、Excel数据与业务分析联动
人工智能·excel
Yana.nice14 小时前
Excel中以当前列的数值作为查找条件,查找匹配的行
excel
Teable任意门互动15 小时前
AI原生开源多维表格有哪些?主流开源多维表格对比解析
数据库·开源·excel·钉钉·飞书·开源软件·ai-native
Cloud_Shy61816 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第八章 使用读写包操作 Excel 文件 上篇)
python·数据分析·excel·pandas
Cloud_Shy61817 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(附录 B 高级 VS Code 功能)
vscode·python·jupyter·数据分析·excel
Amctwd19 小时前
【Python】从Excel中按行提取图片
java·python·excel
BullSmall20 小时前
软件开发基线管理--全套 Excel 模板
excel·软件工程
Cloud_Shy6181 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第九章 Excel 自动化 上篇)
python·数据分析·excel·numpy·pandas