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'
Python,openpyxl在设置格式后再加粗首行为什么就报错了呢?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- soar3033 2021-08-18 16:05关注
你的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')
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥30 关于#java#的问题,请各位专家解答!
- ¥20 pcf8563时钟芯片不启振
- ¥20 pip2.40更新pip2.43时报错
- ¥15 换yum源但仍然用不了httpd
- ¥50 C# 使用DEVMOD设置打印机首选项
- ¥15 麒麟V10 arm安装gdal
- ¥20 OPENVPN连接问题
- ¥15 flask实现搜索框访问数据库
- ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
- ¥100 如何用js写一个游戏云存档