好的,我能够复制这个问题。这是pandas
有关的。 pandas 1.1.5 之前一切正常
在 pandas 1.2.0 中他们做到了一些变化 https://pandas.pydata.org/docs/whatsnew/v1.2.0.html
当你实例化的时候pd.ExcelWriter
with
writer = pd.ExcelWriter(filename, engine='openpyxl')`
它会创建大小为 0 字节的空文件并覆盖现有文件,然后在尝试加载它时会出现错误。它不是openpyxl
相关,因为最新版本的openpyxl
它与 pandas 1.1.5 配合良好。
解决方案 - 指定mode='a'
,将上面的行更改为
writer = pd.ExcelWriter(filename, engine='openpyxl', mode='a')
或者 - 看看this https://stackoverflow.com/a/66472617/4046632 or this https://stackoverflow.com/a/20221655/4046632解决方案在实例化之前加载文件pd.ExcelWriter
.
编辑:我在评论中被告知mode='a'
如果文件不存在,它将引发 FileNotFoundError。虽然在这种情况下它不会创建文件是出乎意料的,但解决方案是移动创建writer
现有的内部try
阻止并创建一个writer
与模式w
in the except
part:
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
(c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
"""
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
# Python 2.x: define [FileNotFoundError] exception if it doesn't exist
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
writer = pd.ExcelWriter(filename, engine='openpyxl', mode='a')
# 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
writer = pd.ExcelWriter(filename, engine='openpyxl')
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()