Python使用OpenPyXl设置Excel表格中的单元格大小(行高和列宽)

文章目录

  • 1. 按
  • 2. 设置单行和一列的长和宽
  • 3. 设置所有行和全部列的长和宽

1. 按

本文主要讨论 openpyxl如何设置(调整)单元格大小(行高和列宽),其他功能可参考:Python3 进行读取、修改和写Excel表格(.xlsx文件)的常用功能示例

2. 设置单行和一列的长和宽

from openpyxl import load_workbook
 
wb = load_workbook('test.xlsx')
print(wb.sheetnames)
ws = wb[wb.sheetnames[0]]
 
# 调整列宽
ws.column_dimensions['A'].width = 20.0
 
# 调整行高
ws.row_dimensions[1].height = 40
 
wb.save('test.xlsx')

结果:
运行前:

运行后:

3. 设置所有行和全部列的长和宽

from openpyxl import load_workbook
from openpyxl.utils import get_column_letter


wb = load_workbook('test.xlsx')
print(wb.sheetnames)
ws = wb[wb.sheetnames[0]]

width = 2.0
height = width * (2.2862 / 0.3612)

print("row:", ws.max_row, "column:", ws.max_column)
for i in range(1, ws.max_row+1):
    ws.row_dimensions[i].height = height
for i in range(1, ws.max_column+1):
    ws.column_dimensions[get_column_letter(i)].width = width

wb.save('test.xlsx')

你可能感兴趣的:(Python)