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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog