如何在不覆盖数据的情况下写入现有的 excel 文件(使用 Pandas)? [英] How to write to an existing excel file without overwriting data (using pandas)?

查看:44
本文介绍了如何在不覆盖数据的情况下写入现有的 excel 文件(使用 Pandas)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pandas以下列方式写入excel文件:

I use pandas to write to excel file in the following fashion:

import pandas

writer = pandas.ExcelWriter('Masterfile.xlsx') 

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

Masterfile.xlsx 已经包含许多不同的选项卡.但是,它还不包含Main".

Masterfile.xlsx already consists of number of different tabs. However, it does not yet contain "Main".

Pandas 正确写入主"表,不幸的是它也删除了所有其他标签.

Pandas correctly writes to "Main" sheet, unfortunately it also deletes all other tabs.

推荐答案

Pandas 文档说它使用 openpyxl 来处理 xlsx 文件.快速浏览 ExcelWriter 中的代码会发现类似这样的事情可能会奏效:

Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in ExcelWriter gives a clue that something like this might work out:

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

这篇关于如何在不覆盖数据的情况下写入现有的 excel 文件(使用 Pandas)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆