pandas 在将数据框写入 Excel 工作表时,获取 AttributeError 'Workbook' 对象没有属性 'add_worksheet'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49519696/
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
Getting AttributeError 'Workbook' object has no attribute 'add_worksheet' - while writing data frame to excel sheet
提问by singularity2047
I have following code and trying to write a data frame into an "Existing" worksheet of an Excel file (referred here as test.xlsx). Sheet3 is the targeted sheet, where I want to place the data and I don't want to replace the entire sheet with a new one.
我有以下代码并尝试将数据框写入 Excel 文件的“现有”工作表(此处称为 test.xlsx)。Sheet3 是目标工作表,我想在其中放置数据,但不想用新工作表替换整个工作表。
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) # *I am not sure what is happening in this line*
df.to_excel(writer,"Sheet3",startcol=0, startrow=20)
When I am running the code line by line, I am getting this error for the last line:
当我逐行运行代码时,最后一行出现此错误:
AttributeError: 'Workbook' object has no attribute 'add_worksheet'. Now why am I seeing this error when I am not trying to add worksheet ?
AttributeError: 'Workbook' 对象没有属性 'add_worksheet'。现在为什么当我不尝试添加工作表时会看到此错误?
Note: I am aware of this similar issue Python How to use ExcelWriter to write into an existing worksheetbut its not working for me and I can't comment on that post either.
注意:我知道这个类似的问题Python How to use ExcelWriter to write into an existing worksheet但它对我不起作用,我也无法评论该帖子。
采纳答案by MaxU
Here is a helper function:
这是一个辅助函数:
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
truncate_sheet=False,
**to_excel_kwargs):
"""
Append a DataFrame [df] to existing Excel file [filename]
into [sheet_name] Sheet.
If [filename] doesn't exist, then this function will create it.
Parameters:
filename : File path or existing ExcelWriter
(Example: '/path/to/file.xlsx')
df : dataframe to save to workbook
sheet_name : Name of sheet which will contain DataFrame.
(default: 'Sheet1')
startrow : upper left cell row to dump data frame.
Per default (startrow=None) calculate the last row
in the existing DF and write to the next row...
truncate_sheet : truncate (remove and recreate) [sheet_name]
before writing DataFrame to Excel file
to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
[can be dictionary]
Returns: None
"""
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
try:
# try to open an existing workbook
writer.book = load_workbook(filename)
# get the last row in the existing Excel sheet
# if it was not specified explicitly
if startrow is None and sheet_name in writer.book.sheetnames:
startrow = writer.book[sheet_name].max_row
# truncate sheet
if truncate_sheet and sheet_name in writer.book.sheetnames:
# index of [sheet_name] sheet
idx = writer.book.sheetnames.index(sheet_name)
# remove [sheet_name]
writer.book.remove(writer.book.worksheets[idx])
# create an empty sheet [sheet_name] using old index
writer.book.create_sheet(sheet_name, idx)
# copy existing sheets
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
except FileNotFoundError:
# file does not exist yet, we will create it
pass
if startrow is None:
startrow = 0
# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)
# save the workbook
writer.save()
Usage:
用法:
append_df_to_excel('test.xlsx', df, sheet_name="Sheet3", startcol=0, startrow=20)
Some details:
一些细节:
**to_excel_kwargs
- used in order to pass additional namedparameters to df.to_excel()
like i did in the example above - parameter startcol
is unknown to append_df_to_excel()
so it will be treated as a part of **to_excel_kwargs
parameter (dictionary).
**to_excel_kwargs
- 用于传递额外的命名参数,df.to_excel()
就像我在上面的例子中所做的那样 - 参数startcol
未知,append_df_to_excel()
因此它将被视为**to_excel_kwargs
参数(字典)的一部分。
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
is used in order to copy existing sheets to writer
openpyxl object. I can't explain why it's not done automatically when reading writer = pd.ExcelWriter(filename, engine='openpyxl')
- you should ask authors of openpyxl
module about that...
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
用于将现有工作表复制到writer
openpyxl 对象。我无法解释为什么在阅读时它没有自动完成writer = pd.ExcelWriter(filename, engine='openpyxl')
- 你应该向openpyxl
模块的作者询问这个......
回答by iDrwish
You can use openpyxl
as the engine when you are creating an instance of pd.ExcelWriter
.
您可以openpyxl
在创建pd.ExcelWriter
.
import pandas as pd
import openpyxl
df1 = pd.DataFrame({'A':[1, 2, -3],'B':[1,2,6]})
book = openpyxl.load_workbook('examples/ex1.xlsx') #Already existing workbook
writer = pd.ExcelWriter('examples/ex1.xlsx', engine='openpyxl') #Using openpyxl
#Migrating the already existing worksheets to writer
writer.book = book
writer.sheets = {x.title: x for x in book.worksheets}
df1.to_excel(writer, sheet_name='sheet4')
writer.save()
Hope this works for you.
希望这对你有用。
回答by Charlie Clark
openpyxl has support for Pandas dataframes so you're best off using it directly. See http://openpyxl.readthedocs.io/en/latest/pandas.htmlfor more details.
openpyxl 支持 Pandas 数据帧,所以你最好直接使用它。有关更多详细信息,请参阅http://openpyxl.readthedocs.io/en/latest/pandas.html。