我已经检查了许多不同的选项来打开已知密码的 Excel 文件,但我无法做到这一点。
我创建了一个 Excel 文件“test_file.xlsx”并使用密码“123”保存。我确实知道其中的内容,并且我想通过 Python 操作它们。这些是我咨询过的主要来源,但没有一个对我有用:
从受密码保护的 Excel 文件到 pandas DataFrame
https://thenethawks.com/python-from-password-protected-excel-file-to-pandas-dataframe/
我正在使用 Jupyter Notes (Anaconda):
import win32com.client
import csv
import sys
import pandas as pd
from tempfile import NamedTemporaryFile
xlApp = win32com.client.Dispatch("Excel.Application")
filename, password = r"test_file.xslx", "123"
# Note this line from the question posted
xlwb = xlApp.Workbooks.Open(filename, False, True, None, password)
xlws = xlwb.Sheets(1) # index is from 1
print (xlws.Name)
print (xlws.Cells(1, 1)) # if you need cell values
f = NamedTemporaryFile(delete=False, suffix='.csv')
f.close()
os.unlink(f.name)
xlCSVWindows = 0x17 # CSV file format, from enum XlFileFormat
xlwb.SaveAs(Filename=f.name, FileFormat=xlCSVWindows) # Save as CSV
df = pd.read_csv(f.name)
print(df.head())
df.to_csv("myoutput.csv",index=False)
这是我到目前为止复制和改编的代码,但是当我运行它时,它显示:
---------------------------------------------------------------------------
com_error Traceback (most recent call last)
<ipython-input-38-a529ec4251c6> in <module>
31
32 # Note this line from the question posted
---> 33 xlwb = xlApp.Workbooks.Open(filename, False, True, None, password)
34
35 xlws = xlwb.Sheets(1) # index is from 1
~\AppData\Local\Temp\gen_py\3.8\00020813-0000-0000-C000-000000000046x0x1x9.py in Open(self, Filename, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
41187 , Editable=defaultNamedOptArg, Notify=defaultNamedOptArg, Converter=defaultNamedOptArg, AddToMru=defaultNamedOptArg, Local=defaultNamedOptArg
41188 , CorruptLoad=defaultNamedOptArg):
> 41189 ret = self._oleobj_.InvokeTypes(1923, LCID, 1, (13, 0), ((8, 1), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)),Filename
41190 , UpdateLinks, ReadOnly, Format, Password, WriteResPassword
41191 , IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify
com_error: (-2147352567, 'Ocurrió una excepción.', (0, 'Microsoft Excel', 'Lo sentimos, no hemos encontrado test_file.xlsx. ¿Puede ser que lo haya movido, eliminado o le hayas cambiado el nombre?', 'xlmain11.chm', 0, -2146827284), None)
最后一行西班牙语说“抱歉,我们找不到 test_file.xlsx。难道我已经移动、删除或重命名了它?”
代码中的第 8 行说
filename, password = r"test_file.xslx", "123"
Excel 文件扩展名应为 xlsx。
将xslx修改为xlsx试试是否有效
filename, password = r"test_file.xlsx", "123"