How do I read a password protected .xlsx file within a zip file in python?

Viewed 113

This is how I read in password protected excel files:

xlApp = win32com.client.Dispatch("Excel.Application")
wb = xlApp.Workbooks.Open(filename, 0, True, None, password)
wb.SaveAs(filename[:-5] + 'Unprotected' + filename[-5:], None, '', '')
wb.Close(False)
df = pd.read_excel(filename[:-5] + 'Unprotected' + filename[-5:], sheet_name=None)
os.remove(base_folder + folder + filename[:-5] + 'Unprotected' + filename[-5:])

This is how i read in files within a folder:

with zipfile.ZipFile(base_folder + folder + filename) as z:
    df = {}
    for file in z.namelist():
       if not os.path.isdir(filename):
            if file.endswith('.xlsx') or file.endswith('.xls'):
                  df[file] = pd.read_excel(io.BytesIO(z.read(file, pwd=bytes(filename[:-4], 'utf-8'))))

I want to put the two together but win32 seems to need a directory rather than BytesIO. I'd rather not have to extract the zip.

0 Answers
Related