Warm tip: This article is reproduced from serverfault.com, please click

python-如何在不覆盖数据的情况下(使用 pandas )写入现有的excel文件?

(python - How to write to an existing excel file without overwriting data (using pandas)?)

发布于 2013-11-26 14:05:22

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

import pandas

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

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

writer.save()

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

pandas 正确地写入“主”表,不幸的是,它也删除了所有其他标签。

Questioner
BP_
Viewed
0
2,511 2020-03-15 12:31:33

pandas 文档表示,它对xlsx文件使用openpyxl。快速浏览一下其中的代码ExcelWriter可以提示可能会发生以下情况:

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()