简体   繁体   中英

BadZipFile with load_workbook

I'm trying to add dataframe's data to an existing xlsx file.

This is my code:

#Files' infos
filename = 'data.xlsx'
sheet_name = 'Sheet1'

if not os.path.isfile(filename):
    df.to_excel(
        filename,
        sheet_name=sheet_name, 
        startrow=startrow if startrow is not None else 0, 
        **to_excel_kwargs)
    

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}

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()

I get this error though: zipfile.BadZipFile: File is not a zip file

I tried to writer.save() and close before the load_workbook but I keep getting the same error.

I also deal with this problem with the same code while I tried to install the package 'pandas' and 'openpyxl' with default pip3 version.

However, I tried to use conda to install 'pandas', 'openpyxl' and it worked.

Then, I reinstalled the same version to pip3 and it worked in pip3, too. I thought the version of the package matters.

Here is how I do

pip3 install pandas==1.1.1 openpyxl==3.0.5 jinja2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM