我使用 pandas 以下列方式写入 excel 文件:
import pandas
writer = pandas.ExcelWriter('Masterfile.xlsx')
data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
writer.save()
Masterfile.xlsx 已经包含许多不同的选项卡。但是,它还没有包含“Main”。
Pandas 正确写入“主”工作表,不幸的是它还删除了所有其他选项卡。
最佳答案
Pandas 文档说它使用 openpyxl 处理 xlsx 文件。快速浏览 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()
关于python - 如何在不覆盖数据的情况下写入现有的 excel 文件(使用 pandas)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20219254/