Help with import error 'BadZipFile' from 'openpyxl'

Options
AS14
AS14 Registered Posts: 1

How do I deal with this error -

I am getting this error:

Error in Python process: At line 7: <class 'ImportError'>: cannot import name 'BadZipFile' from 'openpyxl' (/data/DATA_DIR/code-envs/python/ERM_Python_38/lib/python3.8/site-packages/openpyxl/__init__.py)

this is my library code:

import dataiku
import pandas as pd, numpy as np
from pandas import ExcelWriter
from openpyxl import load_workbook, BadZipFile

def is_valid_excel(file_name):
try:
load_workbook(file_name)
return True
except BadZipFile:
return False

def write_dataframe_to_excel(file_name, sheetname, dataframe):
if is_valid_excel(file_name):
# Open the Excel file
writer = pd.ExcelWriter(file_name, mode="a", engine="openpyxl", if_sheet_exists="replace")

with writer:
dataframe.to_excel(writer, sheet_name=sheetname, index=False)

# Save the changes and close the Excel file
writer.save()
else:
# If the file is not a valid Excel file, create a new one
writer = pd.ExcelWriter(file_name, engine="openpyxl")

with writer:
dataframe.to_excel(writer, sheet_name=sheetname, index=False)

# Save the changes and close the Excel file
writer.save()

Answers

  • JordanB
    JordanB Dataiker, Dataiku DSS Core Designer, Dataiku DSS Adv Designer, Registered Posts: 293 Dataiker
    Options

    Hi @AS14
    ,

    You'll need to replace 'from openpyxl import BadZipFile' with:

    <span class="hljs-keyword">from</span> zipfile <span class="hljs-keyword">import</span> BadZipFile
    Let me know if you have any questions.
    Thanks!
    Jordan
Setup Info
    Tags
      Help me…