因工作要求,必须对所有文件加密码。
包括DOCX和XLSX。
调用WIN32COM,刚开始用
win32com. client. Dispatch("Excel.Application"),怎么也打不开,后来各种搜索发现,原来是因为我电脑没装微软excel程序,装的是wps所以得用
app=win32com. client. Dispatch("Wps.Application")
然后
app.Documents. Open("D:/123.docx")
就可以打开了。但是
app=win32com. client.Dispatch("Et.Application")
app.Documents. Open("D:/123.xlsx")
就是打不开。
刚刚才发现,得用
app. Worbook. Open("D:/123.xlsx")
才行。
注意:Wps的正式版是Dispatch("Wps.Application") 和Dispatch("Et.Application"),开发版则加K:
Dispatch("Kwps.Application") 和Dispatch("Ket.Application")
最后当然是上代码:
import win32com.client as wc
import os
path = os.getcwd().replace("\\", "/")
for file in os.listdir(path):
if (".et" in file or ".wps" in file or ".docx" in file or ".xlsx" in file or "doc" in file or "xls" in file) and \
("模板" not in file and ".whl" not in file and ".py" not in file and ".tmp" not in file):
print(file)
try:
app = wc.Dispatch("Kwps.Application") if (".wps" in file or "doc" in file or ".docx" in file) else wc.Dispatch("Ket.Application")
#app = wc.Dispatch("Kwps.Application")
doc = app.Documents.Open(path + "/" +file) if (".wps" in file or "doc" in file or ".docx" in file) else app.Workbooks.Open(path + "/" +file)
doc.Password = "123123123"
doc.SaveAs(path + "/加密码_" +file)
#doc.Save() #
doc.Close()
app.Quit()
print("成功了")
except Exception as e:
print("出错了:", e)
pass