一、前言
今天学习了使用Python的openpyxl库,来设置excel单元格的字体风格,以及调整单元格的行高和列宽。把学习的过程分享给大家。大佬勿喷!
二、程序展示
1、设置单元格字体风格
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet1 = wb.active
font = Font(size=36, italic=True)
sheet1['B2'] = 'My Style'
cell = sheet1['B2']
cell.font = font
wb.save('F:\python_study\表格\my1excel.xlsx')
这里通过引入openpyxl.styles的font,实现字体的大小和字体格式的调整,字体设置为36,字体格式为“italic”。在B2单元格输入了“My Style”。
运行的记过如下:
2、设置单元格行高和列宽
上面的截图中,文字内容的大小明显超过了单元格本来的大小,在这里可以通过设置单元格大小来进行调整。通过下面两行代码来实现单元格高度和宽度的设置。
sheet1.row_dimensions[2].height = 40
sheet1.column_dimensions['B'].width = 40
完整的代码如下:
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet1 = wb.active
font = Font(size=36, italic=True)
sheet1['B2'] = 'My Style'
cell = sheet1['B2']
cell.font = font
sheet1.row_dimensions[2].height = 40
sheet1.column_dimensions['B'].width = 40
wb.save('F:\python_study\表格\my1excel.xlsx')
运行后的记过如下:
通过程序设置后,excel 第2行的高度和第2列的宽度就固定了下来。