我正在使用Windows 7,Python 2.7和Microsoft Excel 2013。
我从here知道我可以使用以下示例代码打开并访问受密码保护的Excel工作表:
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工作表保存为Python对象。理想情况下,它将保存为pandas dataframe
,但我可以将其作为字典或任何其他对象类型。
我有密码。这可能吗?
谢谢!
答案 0 :(得分:3)
将以下行添加到现有代码中(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 SaveAs参考:https://msdn.microsoft.com/en-us/library/bb214129(v=office.12).aspx