Unprotect an Excel file programmatically

不问归期 提交于 2019-11-29 08:28:47

This post helped me a lot. I thought I would post what I used for my solution in case it may help someone else. Just Unprotect, DisaplyAlerts=False, and Save. Made it easy for me and the file is overwritten with a usable unprotected file.

import os, sys
import win32com.client

def unprotect_xlsx(filename):
    xcl = win32com.client.Dispatch('Excel.Application')
    pw_str = '12345'
    wb = xcl.workbooks.open(filename)
    wb.Unprotect(pw_str)
    wb.UnprotectSharing(pw_str)
    xcl.DisplayAlerts = False
    wb.Save()
    xcl.Quit()

if __name__ == '__main__':
    filename = 'test.xlsx'
    unprotect_xlsx(filename)

This function works for me

def Remove_password_xlsx(filename, pw_str):
    xcl = win32com.client.Dispatch("Excel.Application")
    wb = xcl.Workbooks.Open(filename, False, False, None, pw_str)
    xcl.DisplayAlerts = False
    wb.SaveAs(filename, None, '', '')
    xcl.Quit()

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!