🐍 Python 自动调整 Excel 行高和列宽的三种方法
在 Python 中,我们可以使用
openpyxl
或pandas
结合openpyxl
来操作 Excel,并自动调整行高和列宽。本文将介绍三种实用的方法,并对比它们的适用场景与优缺点。
✅ 方法一:使用 openpyxl
(推荐)
openpyxl
是专门用于读写 Excel 的第三方库,支持 .xlsx
和 .xlsm
格式,适合对已有 Excel 文件进行读取和修改。
🔧 安装
pip install openpyxl
💡 示例代码
import openpyxl
# 加载 Excel 文件
wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active # 获取活动工作表
# 自动调整列宽
for col in ws.columns:
max_length = 0
column = col[0].column_letter # 获取列的字母标识(如 A, B, C)
for cell in col:
try:
if cell.value and len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length +