使用 Openpyxl 和现有工作簿的 Pandas Excel Writer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45220247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Excel Writer using Openpyxl with existing workbook
提问by MattR
I have code from a while ago that I am re-using for a new task. The task is to write a new DataFrame into a new sheet, into an existing excel file. But there is one part of the code that I do not understand, but it just makes the code "work".
我有一段时间前的代码,我将其重新用于新任务。任务是将一个新的 DataFrame 写入一个新的工作表,写入一个现有的 excel 文件。但是有一部分代码我不明白,但它只是使代码“工作”。
working:
在职的:
from openpyxl import load_workbook
import pandas as pd
file = r'YOUR_PATH_TO_EXCEL_HERE'
df1 = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook(file)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.book = book # <---------------------------- piece i do not understand
df1.to_excel(writer, sheet_name='New', index=None)
writer.save()
The little line of writer.book=book
has me stumped. Without that piece of code, the Excel file will delete all other sheets, except the sheet used in the sheetname=
parameter in df1.to_excel
.
的小线writer.book=book
让我难住了。如果没有一段代码,Excel文件将删除所有其它片材,除了在使用的片材sheetname=
中的参数df1.to_excel
。
i looked at xlsxwriter
'sdocumentation as well as openpyxl
's, but cannot seem to figure out whythat line gives me my expected output. Any ideas?
我看着xlsxwriter
的文档以及openpyxl
的,但似乎无法弄清楚,为什么这条线给我我预期的输出。有任何想法吗?
edit: i believe this postis where i got the original idea from.
编辑:我相信这篇文章是我最初想法的来源。
采纳答案by Aritesh
In the source code of ExcelWriter, with openpyxl, it initializes empty workbook and delete all sheets. That's why you need to add it explicitly
ExcelWriter源代码中,使用openpyxl初始化空工作簿并删除所有工作表。这就是为什么你需要明确添加它
class _OpenpyxlWriter(ExcelWriter):
engine = 'openpyxl'
supported_extensions = ('.xlsx', '.xlsm')
def __init__(self, path, engine=None, **engine_kwargs):
# Use the openpyxl module as the Excel writer.
from openpyxl.workbook import Workbook
super(_OpenpyxlWriter, self).__init__(path, **engine_kwargs)
# Create workbook object with default optimized_write=True.
self.book = Workbook()
# Openpyxl 1.6.1 adds a dummy sheet. We remove it.
if self.book.worksheets:
try:
self.book.remove(self.book.worksheets[0])
except AttributeError:
# compat
self.book.remove_sheet(self.book.worksheets[0])