JimR
JimR

Reputation: 131

Unprotect an Excel file programmatically

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?

Upvotes: 10

Views: 60673

Answers (7)

Simonas Audickas
Simonas Audickas

Reputation: 1

Use this code:

import subprocess
subprocess.run(["soffice", "--headless", "--convert-to", "xlsx", filename], check=True)

Upvotes: 0

Nick Crews
Nick Crews

Reputation: 916

The solution that just worked for me on mac was https://github.com/nolze/msoffcrypto-tool. It even has a CLI!

If you have uv installed it's a one-liner:

uvx msoffcrypto-tool encrypted.xlsx decrypted.xlsx -p PaSsWoRd

Otherwise, its a two-liner

python -m pip install msoffcrypto-tool
msoffcrypto-tool encrypted.xlsx decrypted.xlsx -p PaSsWoRd

but there is a python API too if you need to do something more complicated.

Upvotes: 1

Alireza Heidary
Alireza Heidary

Reputation: 81

you can unprotect excel file sheets with python openpyxl module without knowing the password:

from openpyxl import load_workbook
sample = load_workbook(filename="sample.xlsx")
for sheet in sample: sheet.protection.disable()
sample.save(filename="sample.xlsx")
sample.close()

where parameter "filename" is the path of your excel file which in here i have used local dir path.

Upvotes: 8

Daniel Hasegan
Daniel Hasegan

Reputation: 795

if you are on MacOS (or maybe Linux? not tested)

You have to install Microsoft Excel and xlwings

pip install xlwings

Then run this:

import pandas as pd
import xlwings as xw

def _process(filename):
  wb = xw.Book(filename)
  sheet = wb.sheets[0]
  df = sheet.used_range.options(pd.DataFrame, index=False, header=True).value
  wb.close()
  return df

Resources:

Upvotes: 2

Enoch Sit
Enoch Sit

Reputation: 171

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()

Upvotes: 17

Colin
Colin

Reputation: 281

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)

Upvotes: 7

JimR
JimR

Reputation: 131

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.

Upvotes: 2

Related Questions