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处理完成!")

调整后结果

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

相关推荐
福兮说3 小时前
在浏览器里写一个“够用就好“的 Excel 公式求值器
前端·javascript·excel·编译原理
慧都小妮子19 小时前
标签打印如何减少手工抄数?用Bartender 直连 Excel 批量打印
excel·bartender·条码打印·标签打印软件·数据驱动打印·工业打印机
SunnyDays10111 天前
Java 设置 Excel 数据验证:整数、日期、文本长度、下拉列表和时间
java·excel·数据验证·下拉列表
Metaphor6921 天前
使用 Python 设置 Excel 行列自适应 【代码示例】
python·excel
用户0332126663672 天前
使用 Python 设置 Excel 行列自适应 【代码示例】
python·excel
企业数字化笔记2 天前
固定资产Excel批量导入怎么防重复?资产编码、重复检查和错误回执
java·后端·excel
CORNERSTONE3652 天前
低代码开发有哪些应用场景?
低代码·excel·erp·mes·企业数字化
小葱炖豆腐3 天前
python绘制excel折线图
python·excel·numpy·pandas·matplotlib
cspttty3 天前
2026年财务分析岗JD中的Excel、SQL、BI与业务分析要求
大数据·sql·excel
cspttty3 天前
HR数字化校招准备路线:Excel、SQL、BI和AI工具怎么学
人工智能·sql·excel