How to unlock password-protected Excel in Python

Python

I couldn’t find a way to set and remove the Excel read password in Python, so I’m leaving it in this article.

Conclusion code first.

import win32com.client

excel = win32com.client.Dispatch('Excel.Application')
book = excel.Workbooks.Open('sample.xlsx', Password='password')

excel.DisplayAlerts = False
book.SaveAs('sample.xlsx', Password='')
excel.DisplayAlerts = True

book.Close()

The above code works on windows, it didn’t work on mac, which is not surprising since it uses win32.

The following is a careful explanation.

Install required modules

Install ‘ pywin32 ‘ with pip as it uses win32com.client.

pip install pywin32

Code to open and close an Excel file with read password

import win32com.client

excel = win32com.client.Dispatch('Excel.Application')
book = excel.Workbooks.Open('sample.xlsx', Password='password')

book.Close()

Import win32com.client on line 1

Instantiate by specifying Excel.Application in the Dispatch class in line 3

Open an Excel file named sample.xlsx in line 4, specifying ‘password’ as the password.

Please read sample.xlsx and the ‘ password ‘ part in your own environment.

Overwrite and save without password

import win32com.client

excel = win32com.client.Dispatch('Excel.Application')
book = excel.Workbooks.Open('sample.xlsx', Password='password')

book.SaveAs('sample.xlsx', Password='')

book.Close()

Specify the name of the file to be saved in book.SaveAs (in this case, overwrite it with sample.xlsx. You can also save the file under a different name), and specify a new password (in this case, specify no password).

The above code will cause a confirmation dialog to be displayed, making it necessary to click on the screen.

Set read password and close

Specify no password when opening the file and a new password when saving (here ‘password’)

import win32com.client

excel = win32com.client.Dispatch('Excel.Application')
book = excel.Workbooks.Open('sample.xlsx', Password='')

excel.DisplayAlerts = False
book.SaveAs('sample.xlsx', Password='password')
excel.DisplayAlerts = True

book.Close()

summary

Completed Version Code. The following code will overwrite the read password removed.

import win32com.client

excel = win32com.client.Dispatch('Excel.Application')
book = excel.Workbooks.Open('sample.xlsx', Password='password')

excel.DisplayAlerts = False
book.SaveAs('sample.xlsx', Password='')
excel.DisplayAlerts = True

book.Close()

コメント

タイトルとURLをコピーしました