import openpyxl
from openpyxl.styles import Font, Alignment
book = openpyxl.load_workbook('测试.xlsx')
ws = book.active
ws.column_dimensions['B'].width = 25
ws.column_dimensions['C'].width = 15
ws.column_dimensions['E'].width = 40
for i in range(1, ws.max_row + 1):
ws.row_dimensions[i].height = 12.75
for col in ws.columns:
for cell in col:
font = Font(name='Arial', size=10)
cell.font = font
cell.alignment = Alignment(vertical='center')
# 下面设置首行加粗就报错了(A1:F1),上面都能正常运行,不带下面for循环能正常保存表格
for cell in range(6):
font = Font(name='Arial', size=10, bold=False)
cell.font = font
book.save('测试-输出.xlsx')
报错内容:
'int' object has no attribute 'font'
你的for cell in range(6) cell不是单元格对象,是数字,当然报错
改成这样
import openpyxl
from openpyxl.styles import Font, Alignment
book = openpyxl.load_workbook('测试.xlsx')
ws = book.active
ws.column_dimensions['B'].width = 25
ws.column_dimensions['C'].width = 15
ws.column_dimensions['E'].width = 40
for i in range(1, ws.max_row + 1):
ws.row_dimensions[i].height = 12.75
for col in ws.columns:
for cell in col:
font = Font(name='Arial', size=10)
cell.font = font
cell.alignment = Alignment(vertical='center')
# 下面设置首行加粗就报错了(A1:F1),上面都能正常运行,不带下面for循环能正常保存表格
count=0
for i in ws.columns:
count+=1
if count>6:
break
cell=i[0]
font = Font(name='Arial', size=40, bold=False)
cell.font = font
book.save('测试-输出.xlsx')