Lazulitecn 2021-08-18 15:49 采纳率: 84.8%
浏览 50
已结题

Python,openpyxl在设置格式后再加粗首行为什么就报错了呢?


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'
  • 写回答

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')
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月26日
  • 已采纳回答 8月18日
  • 创建了问题 8月18日

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程