使用openpyxl给Excel最大行设置边框报Int对象不可迭代错误如何解决
问题解决说明
报错根因
sheet.max_row返回的是代表工作表最大行数的整数值,直接对整数进行遍历操作不符合Python语法规则,因此触发'Int' object is not iterable报错。
可直接运行的实现代码
你只需要调整遍历逻辑,改为遍历最大行对应的单元格对象即可实现需求,修正后的代码如下:
from openpyxl.styles import Border, Side # 预定义边框样式 thin_side = Side(border_style="thin", color="000000") full_border = Border(top=thin_side, left=thin_side, right=thin_side, bottom=thin_side) # 获取最大行号 max_row_num = sheet.max_row # 遍历最大行的所有单元格设置边框 for cell in sheet[max_row_num]: cell.border = full_border
如果需要限定边框设置的列范围,可以改用按坐标访问单元格的写法:
from openpyxl.styles import Border, Side thin_side = Side(border_style="thin", color="000000") full_border = Border(top=thin_side, left=thin_side, right=thin_side, bottom=thin_side) max_row_num = sheet.max_row max_col_num = sheet.max_column # 仅在第1列到最大列的范围内设置最大行的边框 for col_idx in range(1, max_col_num + 1): sheet.cell(row=max_row_num, column=col_idx).border = full_border
注意事项
- 原代码导入语句末尾多了多余的逗号,需删除避免语法报错
- 提前复用定义好的边框对象,无需在循环中重复生成,可提升运行效率
内容的提问来源于stack exchange,提问作者Bobby
相关产品推荐
相关产品推荐

