【发布时间】:2021-03-12 20:59:10
【问题描述】:
使用最新的包版本:openpyxl: 3.0.6 |熊猫:1.2.3 |python:3.9
在将上面的软件包更新到报告的最新版本之前,下面的功能运行良好。
现在它引发错误:“zipfile.BadZipFile: File is not a zip file”。
这样的功能真的很有用,如果知道它是否可以修复以使其正常工作会很高兴。
下面的函数可以直接运行,只需将“pathExport”替换为你的导出目录进行测试。
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')
writer = pd.ExcelWriter(filename, engine='openpyxl')
# Python 2.x: define [FileNotFoundError] exception if it doesn't exist
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
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()
pathExport = r"F:\PYTHON\NB-Suite_python39\MNE\outputData\df.xlsx"
df1 = pd.DataFrame({'numbers': [1, 2, 3],
'colors': ['red', 'white', 'blue'],
'colorsTwo': ['yellow', 'white', 'blue']
})
append_df_to_excel(pathExport, df1, sheet_name="DF1", index=False, startcol=0, startrow=0)
【问题讨论】:
-
这看起来像 #66471466 的副本,我认为这是因为 Pandas 用空文件覆盖了现有工作簿。处理后只需为文件使用不同的名称即可。
-
@CharlieClark 请问我应该在哪里更改函数中的名称?所以我可以试一试,如果可行,请让用户在这里,提前感谢
-
而不仅仅是
filename使用source_filename与 openpyxl 和target_filename与 Pandas。请注意,两者肯定是不同的。 -
@CharlieClark 谢谢。我尽了最大努力,但我不确定我应该在哪里进行这些更改。你能用已经修复的代码回复吗?所以我可以对其进行测试并确认它是否有效,我相信它会对所有其他将在这里阅读的用户有用,谢谢
-
快速更新:刚刚注意到“leeprevost”在帖子#20219254 上提出了完全相同的问题,就在@MaxU 的回答下,但仍然没有得到回答
标签: pandas openpyxl xlsx python-3.9