From Password Protected Excel File to Python Object

前提是你 提交于 2019-12-06 12:38:19

问题


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



来源:https://stackoverflow.com/questions/36850716/from-password-protected-excel-file-to-python-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!