簡體   English   中英

從密碼保護的Excel文件到Python對象

[英]From Password Protected Excel File to Python Object

我使用的是Windows 7,Python 2.7和Microsoft Excel 2013。

我從這里知道我可以使用下面的示例代碼打開並訪問受密碼保護的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但我可以將其作為字典或任何其他對象類型。

我有密碼。 這可能嗎?

謝謝!

將以下行添加到現有代碼中(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM