-->

From Password Protected Excel File to Python Objec

2020-07-27 05:53发布

问题:

I am using Windows 7, Python 2.7 and Microsoft Excel 2013.

I know from here that I can open and access a password protected Excel sheet using the below sample code:

import sys
import win32com.client
xlApp = win32com.client.Dispatch("Excel.Application")
print "Excel library version:", xlApp.Version
filename, password = sys.argv[1:3]
xlwb = xlApp.Workbooks.Open(filename, Password=password)
# xlwb = xlApp.Workbooks.Open(filename)
xlws = xlwb.Sheets(1) # counts from 1, not from 0
print xlws.Name
print xlws.Cells(1, 1) # that's A1

I would like to save an Excel worksheet from a password protected file as a Python object. Ideally it would be saved as a pandas dataframe but I would be OK to have it as a dictionary or any other object type.

I have the password. Is this possible?

Thanks!

回答1:

Add the following lines to your existing code (where xlwb already exists):

import os
import pandas as pd
from tempfile import NamedTemporaryFile

# Create an accessible temporary file, and then delete it. We only need a valid path.
f = NamedTemporaryFile(delete=False, suffix='.csv')  
f.close()
os.unlink(f.name)  # Not deleting will result in a "File already exists" warning

xlCSVWindows = 0x17  # CSV file format, from enum XlFileFormat
xlwb.SaveAs(Filename=f.name, FileFormat=xlCSVWindows)  # Save the workbook as CSV
df = pd.read_csv(f.name)  # Read that CSV from Pandas
print df

Bear in mind that for me your code didn't fully work, and I got prompted for a password. But assuming you do manage to read a password protected file, the code above works.

Excel SaveAs reference: https://msdn.microsoft.com/en-us/library/bb214129(v=office.12).aspx