以编程方式取消保护 Excel 文件

时间:2023-04-16
本文介绍了以编程方式取消保护 Excel 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我们从一个启用了打开保护和写入保留保护的客户端获取了一个 Excel 文件.我想删除保护,以便可以使用 python xlrd 模块打开 Excel 文件.我已经安装了 pywin32 包以通过 COM 访问 Excel 文件,我可以使用提供两个密码的程序打开它,保存并关闭文件而没有错误.我正在使用 MSDN 网络中描述的 Unprotect 命令,它们没有失败,但它们也没有删除保护.在我的程序完成后,保存的文件仍然需要两个密码才能打开它.到目前为止,这是我所拥有的:

We're getting an Excel file from a client that has open protection and Write Reserve protection turned on. I want to remove the protection so I can open the Excel file with the python xlrd module. I've installed the pywin32 package to access the Excel file through COM, and I can open it with my program supplying the two passwords, save, and close the file with no errors. I'm using Unprotect commands as described in MSDN network, and they're not failing, but they're also not removing the protection. The saved file still requires two passwords to open it after my program is done. Here's what I have so far:

import os, sys
impdir = "\\xxx.x.xx.x\allshare\IT\NewBusiness\Python_Dev\import\"
sys.path.append(impdir)
from UsefulFunctions import *
import win32com.client

wkgdir = pjoin(nbShare, 'NorthLake\_testing')
filename = getFilename(wkgdir, '*Collections*.xls*')
xcl = win32com.client.Dispatch('Excel.Application')
xcl.visible = True
pw_str = raw_input("Enter password: ")
try:
    wb = xcl.workbooks.open(filename, 0, False, None, pw_str, pw_str)
except Exception as e:
    print "Error:", str(e)
    sys.exit()
wb.Unprotect(pw_str)
wb.UnprotectSharing(pw_str)
wb.Save()
xcl.Quit()

谁能提供正确的解除保护命令的语法?

Can anyone provide me the correct syntax for unprotect commands that will work?

推荐答案

@Tim Williams 的建议奏效了.(使用 SaveAs 并为 Password 和 WriteResPassword 参数传递空字符串.)我在文件名后面的 'format' 参数中使用了 'None',并且我使用了新的文件名来防止 Excel 提示我询问是否可以覆盖现有文件.我还发现我不需要使用这种方法的 wb.Unprotect 和 wb.UnprotectSharing 调用.

The suggestion from @Tim Williams worked. (Use SaveAs and pass empty strings for the Password and WriteResPassword parameters.) I used 'None' for the 'format' parameter after filename, and I used a new filename to keep Excel from prompting me asking if OK to overwrite the existing file. I also found that I did not need the wb.Unprotect and wb.UnprotectSharing calls using this approach.

这篇关于以编程方式取消保护 Excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:为什么致命错误:安装 PyYAML 时找不到“yaml.h"文件? 下一篇:如何在 Python 中声明一个静态属性?

相关文章