Xlwings / open password protected xlsx? - python

is there any way to open a password protected excel-sheet with xlwings?
(whole xlsx is protected - that means when the excel is opened you have to put in a password to get to the excel)
If not is there any other way to protect the excel-sheet for some users - but have access with xlwings to the worksheet?

xlwings.Book() has a password parameter:
password (str) – Password to open a protected workbook
You should just be able to
import xlwings
wb = xlwings.Book("file.xlsx", password="Passw0rd!")

Related

Edit read-only password protected excel with Python

I am trying to find a way to edit a password protected excel with Python. Password is not required to open the excel, it is only required if you want to edit it:
Is it possible to access this using password and edit it? Would be perfect if it would be possible to edit it using Openpyxl. I have already tried to use msoffcrypto:
decrypted = io.BytesIO()
with open("encrypted.xlsx", "rb") as f:
file = msoffcrypto.OfficeFile(f)
file.load_key(password="Passw0rd") # Use password
file.decrypt(decrypted)
df = pd.read_excel(decrypted)
But I think this works only when you can access the file only with password (the whole file is password encrypted, not the edit part.
If the Excel workbook has been saved with a "Password to modify" like in Office 2011 then you you usually need to perform following steps in Excel to save an unprotected version:
enter the password
open the workbook (still it is write-protected)
save as (unprotected)
In Python
You can decrypt it using a password and then pass the decrypted byte stream - as file-like object - to the opening function, be it pandas.read_excel() or openpyxl.load_workbook():
import io
import msoffcrypto
import openpyxl
decrypted_workbook = io.BytesIO()
with open('encrypted.xlsx', 'rb') as file:
office_file = msoffcrypto.OfficeFile(file)
office_file.load_key(password='passw0rd')
office_file.decrypt(decrypted_workbook)
# `filename` can also be a file-like object.
workbook = openpyxl.load_workbook(filename=decrypted_workbook)
See also:
Reading encrypted file with pandas
How to open a password protected excel file using python?
how to read password protected excel in python

How to check if a large Excel file is protected as quickly as possible?

How to check if excel file is protected with password the fastest way (without trying to open it and placing an exception)?
Updated:
from zipfile import *
from openpyxl import load_workbook
filename = 'Z:\\path_to_file\\qwerty.xlsm' # protected one
try:
wb = load_workbook(filename, data_only=True, read_only=True)
except (BadZipfile) as error:
print(is_zipfile(filename))
A problem is that I got False as an output, thus I cannot get rid of the exception and replace it with is_zipfile() condition.
Solution using the openpyxl library:
import openpyxl
wb = openpyxl.load_workbook(PATH_TO_FILE)
if wb.security.lockStructure == None:
# no password, act accordingly
...
else:
# password, act accordingly
...
You can do this using the protection._password property of a sheet:
wb = openpyxl.load_workbook("C:\\Users\\...\\Downloads\\some_workbook.xlsx")
print(wb.worksheets[0].protection._password)
You can do this for whatever sheet you would like, based off the worksheets in the workbook.
If there is no password, the value is None. Otherwise, it returns the hashed password.
So, you can create a method to check this:
def password_protected(sheet):
if sheet.protection._password is None:
return False
return True
The same method applies for the whole workbook, the property is just workbook.protection._workbook_password.
When trying to open a password protected workbook with openpyxl, this indeed gives a error zipfile.BadZipFile so a workaround would be to use:
import zipfile
zipfile.is_zipfile("workbook.xlsx")

Asking warning message after saving workbook in openpyxl

wb_write = openpyxl.load_workbook(file_path)
first_sheet = wb_write.get_sheet_names()[0]
ws = wb_write.get_sheet_by_name(first_sheet)
#here row=1 ,column= 5
ws.cell(row=i, column=mt_mac_id_column).value = MT_MAC
wb_write.save(file_path)
After writing data into xlsx file and saved in the same workbook.
Opened manually xlsx file in windows Changes are reflected in xlsx file but while closing the xlsx file it is asking for confirmation like "do you want to save the changes you made to file"
Why it is asking for confirmation? How do I avoid this warning?

Create a File using xlwt and send email in Django application

I have created a workbook using xlwt, now I was wondering if I could send an email using this workbook, but a without saving the workbook on disk. I am unable to do a proper implementation where I could send it as an attachment without saving it on disk temporarily. Here is the code for email as an attachment.
file_name = "temp_file_location.xlsx"
book = xlwt.Workbook()
sheet = book.add_sheet("XYZ")
book.save(file_name)
message = EmailMessage(subject="Subject", body="body",
from_email="random#gmail.com",
to=email_list)
message.attach_file(file_name)
message.send()
There is a similar question here:
How to send an email with attachment?
But no solution, and I am unable to send email without saving it on disk temporarily.
Any Ideas?
You can write your workbook in memory using StringIO:
import StringIO
f = StringIO.StringIO() # create a file-like object
book = xlwt.Workbook()
sheet = book.add_sheet("XYZ")
book.save(f)
message = EmailMessage(subject="Subject", body="body",
from_email="random#gmail.com",
to=email_list)
message.attach('filename.xlsx', f.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") #get the stream and set the correct mimetype
message.send()
taken from xlwt write excel sheet on the fly

how to read password protected excel in python

I'm new to python programming, and I am trying to read a password protected file using python, the code is shown below:
import sys
import win32com.client
xlApp = win32com.client.Dispatch("Excel.Application")
print "Excel library version:", xlApp.Version
filename,password = 'C:\myfiles\foo.xls', 'qwerty12'
xlwb = xlApp.Workbooks.Open(filename, Password=password)
But then the xls file is loaded but still prompt me to provide the password, I can't let python to enter the password for me.
What have I done wrong? Thanks!
Open takes two types of password, namely:
Password: password required to open a protected workbook.
WriteResPassword : password required to write to a write-reserved workbook
So in your case , is it write protected or protection on open?
Also there is a discussion on SO that says that this does not work with named parameters, So try providing all parameter values with the defaults
How to open write reserved excel file in python with win32com?
Default values are documented in MSDN
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.open.aspx
Use this to open password protected file
xlwb = xlApp.Workbooks.Open(filename, False, True, None, password)
I hope this works. It worked for me.

Categories