从受密码保护的 Excel 文件到 Python 对象

From Password Protected Excel File to Python Object

我正在使用 Windows 7、Python 2.7 和 Microsoft Excel 2013。

我从 here 得知我可以使用以下示例代码打开和访问受密码保护的 Excel sheet:

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

我想将密码保护文件中的 Excel 作品sheet 保存为 Python 对象。理想情况下,它将保存为 pandas dataframe,但我可以将其保存为字典或任何其他对象类型。

我有密码。这可能吗?

谢谢!

将以下行添加到您现有的代码中(其中 xlwb 已存在):

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

请记住,对我而言,您的代码无法完全正常工作,系统提示我输入密码。但假设您确实设法读取了受密码保护的文件,上面的代码就可以工作了。

Excel 另存为参考:https://msdn.microsoft.com/en-us/library/bb214129(v=office.12).aspx