原理简单:就是每写入一行,然后保存
代码:
import openpyxl
import time
book = openpyxl.Workbook()
sheet = book.active
for i in range(100):
# 每次循环开头重新获取最大行,也是核心
max_row = sheet.max_row
print(f'第{max_row}此循环')
time.sleep(0.1)
# 第一行设置为标题
if max_row == 1:
sheet.cell(row=1, column=1, value=f'第一列')
sheet.cell(row=1, column=2, value=f'第二列')
sheet.cell(row=1, column=3, value=f'第三列')
# 写入第(max_row + 1)行,第一列
sheet.cell(row=max_row + 1, column=1, value=f'写入第{max_row + 1}行,第1列')
# 写入第(max_row + 1)行,第二列
sheet.cell(row=max_row + 1, column=2, value=f'写入第{max_row + 1}行,第2列')
# 写入第(max_row + 1)行,第三列
sheet.cell(row=max_row + 1, column=3, value=f'写入第{max_row + 1}行,第3列')
book.save('result.xlsx')