问题描述
我有以下代码,并尝试将数据帧写入Excel文件的现有"工作表中(此处称为test.xlsx). Sheet3是目标工作表,我想在其中放置数据,并且我不想用新的工作表替换整个工作表.
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.
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:工作簿"对象没有属性"add_worksheet".现在,当我不尝试添加工作表时为什么会看到此错误?
AttributeError: 'Workbook' object has no attribute 'add_worksheet'. Now why am I seeing this error when I am not trying to add worksheet ?
注意:我知道类似的问题,但对我不起作用,我也无法对此帖子发表评论.
Note: I am aware of this similar issue Python How to use ExcelWriter to write into an existing worksheet but its not working for me and I can't comment on that post either.
推荐答案
以下是辅助函数:
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()
用法:
append_df_to_excel('test.xlsx', df, sheet_name="Sheet3", startcol=0, startrow=20)
一些细节:
**to_excel_kwargs
-用于将其他命名参数传递给df.to_excel()
,就像我在上面的示例中所做的那样-append_df_to_excel()
未知参数startcol
,因此将其视为**to_excel_kwargs
参数(词典)的一部分.
**to_excel_kwargs
- used in order to pass additional named parameters 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).
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
用于将现有工作表复制到writer
openpyxl对象.我无法解释为什么在阅读writer = pd.ExcelWriter(filename, engine='openpyxl')
时它不会自动完成-您应该向openpyxl
模块的作者询问...
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...
这篇关于获取AttributeError'Workbook'对象没有属性'add_worksheet'-将数据框写入Excel工作表时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!