Python實(shí)現(xiàn)調(diào)整Excel的內(nèi)容高度
本文介紹了一種自動(dòng)調(diào)整Excel行高的Python實(shí)現(xiàn)方法。通過openpyxl庫(kù)遍歷Excel文件中的每個(gè)工作表,計(jì)算每行文字最多單元格所需的高度(考慮字體大小、換行數(shù)和列寬),自動(dòng)調(diào)整行高以確保內(nèi)容完整顯示。代碼實(shí)現(xiàn)了自動(dòng)計(jì)算行高、批量處理多個(gè)Excel文件的功能,并提供了進(jìn)度提示。該方法可顯著減少手動(dòng)調(diào)整行高的工作量,特別適合處理大量數(shù)據(jù)的Excel文件。使用前需備份原文件,代碼會(huì)直接修改原Excel文件。
背景介紹
有時(shí)在打印EXCEL時(shí),單元格內(nèi)容較多,需多行顯示,類似這樣:

在打印時(shí),需保證單元格內(nèi)的內(nèi)容全部可見。需手動(dòng)調(diào)整每一行高度,如果數(shù)據(jù)行很多,也是不少的工作量。
實(shí)現(xiàn)思路
1.利用程序遍歷EXCEL中的每個(gè)Sheet,遍歷每行。
2.定位該行文字最多那個(gè)單元格。
3.計(jì)算文字最多的單元格高度,單元格寬度,文字大小、換行數(shù)、預(yù)留邊距計(jì)算出該行高度。
4.修改此行高度為第3步計(jì)算出的高度,使得該行所有文本可見。
實(shí)現(xiàn)步驟
1.安裝Python操作EXCEL的庫(kù)
pip install openpyxl
2.編寫代碼
以下代碼會(huì)將代碼所在文件夾下的EXCEL進(jìn)行讀取,并處理行高度。
注意:代碼會(huì)修改原文件,操作前請(qǐng)備份原文件。
#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):
"""
計(jì)算單元格內(nèi)容所需的行高度
:param cell: 單元格對(duì)象
:param column_width: 列寬(以字符數(shù)為單位)
:param padding: 上下留白距離(磅)
:return: 計(jì)算后的行高度(磅)
"""
if cell.value is None:
return None
# 獲取單元格字體信息
font = cell.font
font_size = font.size if font.size else 11
# 獲取單元格內(nèi)容
text = str(cell.value)
# 計(jì)算顯式換行符的行數(shù)
explicit_lines = text.count('\n') + 1
# 考慮列寬計(jì)算自動(dòng)換行
if column_width > 0:
# 計(jì)算文本總字符數(shù)(中文按2個(gè)字符計(jì)算,因?yàn)橹形母鼘挘?
total_chars = 0
for char in text:
if '\u4e00' <= char <= '\u9fff': # 中文字符范圍
total_chars += 3
elif char == '\n':
continue
else:
total_chars += 1
# 根據(jù)列寬和字體大小計(jì)算每行可容納的字符數(shù)
# 字體越大,每行可容納的字符數(shù)越少
font_ratio = 11 / font_size
chars_per_line = column_width * font_ratio
if chars_per_line > 0 and total_chars > 0:
# 計(jì)算自動(dòng)換行所需的行數(shù)
auto_wrap_lines = max(1, int((total_chars + chars_per_line - 1) / chars_per_line))
# 取顯式換行和自動(dòng)換行的較大值
total_lines = max(explicit_lines, auto_wrap_lines)
else:
total_lines = explicit_lines
else:
total_lines = explicit_lines
# 行高計(jì)算:字體大小 * 行數(shù) + 上下留白
base_height = font_size * 1.4
row_height = base_height * total_lines + padding * 2
return row_height
def adjust_excel_row_heights(file_path):
"""
調(diào)整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(" 工作表數(shù)據(jù)不足,跳過")
continue
# 從第2行開始遍歷
for row in range(2, max_row + 1):
max_height = None
# 遍歷當(dāng)前行的所有單元格
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
# 如果計(jì)算出了高度,則設(shè)置行高
if max_height is not None:
ws.row_dimensions[row].height = max_height
# 打印進(jìn)度信息(每10行打印一次)
if (row - 1) % 10 == 0:
print(f" 已處理第 {row} 行,行高設(shè)置為 {max_height:.1f} 磅")
# 保存文件
wb.save(file_path)
print(f"文件 {file_path} 已成功保存!")
except Exception as e:
print(f"處理文件 {file_path} 時(shí)出錯(cuò): {str(e)}")
if __name__ == "__main__":
# 獲取當(dāng)前目錄下所有xlsx文件(排除臨時(shí)文件)
xlsx_files = [f for f in os.listdir('.') if f.endswith('.xlsx') and not f.startswith('~$')]
if not xlsx_files:
print("當(dāng)前目錄下沒有找到Excel文件")
else:
print(f"找到 {len(xlsx_files)} 個(gè)Excel文件")
for file in xlsx_files:
print(f"\n處理文件: {file}")
adjust_excel_row_heights(file)
print("\n處理完成!")調(diào)整后結(jié)果

雖然使用場(chǎng)景不多,不過工作中遇到了,在此記錄一下。
到此這篇關(guān)于Python實(shí)現(xiàn)調(diào)整Excel的內(nèi)容高度的文章就介紹到這了,更多相關(guān)Python調(diào)整Excel內(nèi)容高度內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
玩數(shù)據(jù)必備Python庫(kù)之numpy使用詳解
NumPy提供了許多高級(jí)的數(shù)值編程工具,如矩陣數(shù)據(jù)類型、矢量處理,以及精密的運(yùn)算庫(kù),下面這篇文章主要給大家介紹了關(guān)于玩數(shù)據(jù)必備Python庫(kù)之numpy使用的相關(guān)資料,需要的朋友可以參考下2022-02-02
python基于tkinter制作無損音樂下載工具(附源碼)
這篇文章主要介紹了python基于tkinter制作無損音樂下載工具(附源碼),幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-03-03
python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹
這篇文章主要介紹了python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹,具有很好參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
詳解如何用TensorFlow訓(xùn)練和識(shí)別/分類自定義圖片
這篇文章主要介紹了詳解如何用TensorFlow訓(xùn)練和識(shí)別/分類自定義圖片,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

