You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用openpyxl向Excel最后一行添加数据时出现行错位问题

问题原因

每次调用ws.max_row时,前一次写入单元格会让工作表的最大行号自动增加,导致后续的ws.max_row +1不断指向新行,最终各列数据依次写入下一行。

解决方案

提前计算好要写入的目标行号,统一使用这个固定行号写入所有列的数据:

firstname = input("enter your first name: ")
lastname = input("enter your last name: ")
newpass = input("enter a password: ")
newbalance = input("enter balance: ")
# 提前计算目标行号,避免每次写入后max_row变化
new_row = ws.max_row + 1
ws.cell(column=1, row=new_row, value=firstname)
ws.cell(column=2, row=new_row, value=lastname)
ws.cell(column=4, row=new_row, value=newpass)
ws.cell(column=5, row=new_row, value=newbalance)
wd.save(filename)

内容的提问来源于stack exchange,提问作者Samir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:30:41