pandas在循环中多次写入数据到一个excel防止锁定的方法

啥都不说,都是泪,直接上代码:

python 复制代码
# 在循环中多次写入数据
for i in range(10):
    # 创建一个新的DataFrame
    df = pd.DataFrame({
        'A': [i],
        'B': [i * 2]
    })
    
    # 每次写入后保存文件
    with pd.ExcelWriter('example.xlsx', engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
        df.to_excel(writer, sheet_name='Sheet1', startrow=writer.sheets['Sheet1'].max_row, header=None, index=False)

mode='a' 参数告诉pandas以追加模式打开文件,**if_sheet_exists='overlay' **参数告诉pandas如果工作表已经存在,就覆盖它。这样,每次循环都会将新的数据追加到工作表中,而不会覆盖之前的数据。

相关推荐
2501_930707786 小时前
如何使用C#代码在Excel 文件中添加工作表
excel
shouchaobao11 小时前
免费PDF工具:PDF转Word/Excel/图片+AI总结+合并拆分+OCR识别,多端无广告!
pdf·word·excel
AI小云20 小时前
【数据操作与可视化】Pandas数据处理-其他操作
python·pandas
allbs21 小时前
spring boot项目excel导出功能封装——4.导入
spring boot·后端·excel
m5655bj1 天前
使用 Python 高效复制 Excel 行、列、单元格
开发语言·python·excel
温轻舟2 天前
Python自动办公工具01-Excel文件编辑器
开发语言·python·编辑器·excel·温轻舟
WarPigs2 天前
Unity编辑器开发笔记
unity·编辑器·excel
allbs2 天前
spring boot项目excel导出功能封装——3.图表导出
spring boot·后端·excel
lqz19932 天前
根据html导出excel和word
html·word·excel
12程序猿2 天前
postman调用文件(.xlsm---带宏的excel文件)下载接口成功下载excel文件,浏览器访问下载文件打不开
excel·lua·postman