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

标签 python excel python-2.7 pandas

我使用 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/

相关文章:

python - 将 bash 脚本转换为 python(小脚本)

Python - 显示 json 数据

excel - 从字母数字字符串中提取第一个数字

vba - Excel VBA-单击时如何在多个宏上调用命令按钮?

Python urllib2异常非数字端口: 'port/'

python - 从python字典中删除某些前缀键的有效方法

python - 如何将连字符添加到 Pandas 列中的特定单元格

python - Flask request.form.get 太慢?

python - 在python中登录到base 2

vba - 复制或移动包含表格的一组工作表