Edit read-only password protected excel with Python - 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

Related

How to compress Excel buffer into ZIP buffer?

I'm trying to compress a Excel BytesIO stream into a ZIP BytesIO stream but ValueError: stat: embedded null character in path is called when I use write(). I used pyzipper and pyminizip but neither worked well.
def __compress_excel__(self, excel_buffer):
zip_buffer = BytesIO()
password = b'password'
zip_buffer = pyzipper.AESZipFile(zip_stream, mode='w')
zip_buffer.setpassword(password)
zip_buffer.write(excel_buffer.getvalue())
return zip_buffer.getvalue()
I want to avoid using a temp file to do this. Regards.
UPDATE
Now thanks to martineau comments, Excel could be compressed now, but I have a new problem is that setpassword() from ZipFile doesn't work. A ZIP is created but when in uncompress it, no password is required.
def __compress_excel__(self, excel_buffer):
zip_stream = BytesIO()
password = b'password'
with ZipFile(zip_stream , mode='w') as zipf:
zipf.setpassword(password)
zipf.writestr('excel.xlsx', excel_buffer.getvalue())
return zip_stream.getvalue()
Regards

Xlwings / open password protected xlsx?

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!")

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

Open a protected pdf file in python

I write a pdf cracking and found the password of the protected pdf file. I want to write a program in Python that can display that pdf file on the screen without password.I use the PyPDF library.
I know how to open a file without the password, but can't figure out the protected one.Any idea? Thanks
filePath = raw_input()
password = 'abc'
if sys.platform.startswith('linux'):
subprocess.call(["xdg-open", filePath])
The approach shown by KL84 basically works, but the code is not correct (it writes the output file for each page). A cleaned up version is here:
https://gist.github.com/bzamecnik/1abb64affb21322256f1c4ebbb59a364
# Decrypt password-protected PDF in Python.
#
# Requirements:
# pip install PyPDF2
from PyPDF2 import PdfFileReader, PdfFileWriter
def decrypt_pdf(input_path, output_path, password):
with open(input_path, 'rb') as input_file, \
open(output_path, 'wb') as output_file:
reader = PdfFileReader(input_file)
reader.decrypt(password)
writer = PdfFileWriter()
for i in range(reader.getNumPages()):
writer.addPage(reader.getPage(i))
writer.write(output_file)
if __name__ == '__main__':
# example usage:
decrypt_pdf('encrypted.pdf', 'decrypted.pdf', 'secret_password')
You should use pikepdf library nowadays instead:
import pikepdf
with pikepdf.open("input.pdf", password="abc") as pdf:
num_pages = len(pdf.pages)
print("Total pages:", num_pages)
PyPDF2 doesn't support many encryption algorithms, pikepdf seems to solve them, it supports most of password protected methods, and also documented and actively maintained.
You can use pdfplumber library. Super easy to use and reads machine written pdf files seamlessly, better than any other library i have used.
import pdfplumber
with pdfplumber.open(r'D:\examplepdf.pdf' , password = 'abc') as pdf:
first_page = pdf.pages[0]
print(first_page.extract_text())
I have the answer for this question. Basically, the PyPDF2 library needs to install and use in order to get this idea working.
#When you have the password = abc you have to call the function decrypt in PyPDF to decrypt the pdf file
filePath = raw_input("Enter pdf file path: ")
f = PdfFileReader(file(filePath, "rb"))
output = PdfFileWriter()
f.decrypt ('abc')
# Copy the pages in the encrypted pdf to unencrypted pdf with name noPassPDF.pdf
for pageNumber in range (0, f.getNumPages()):
output.addPage(f.getPage(pageNumber))
# write "output" to noPassPDF.pdf
outputStream = file("noPassPDF.pdf", "wb")
output.write(outputStream)
outputStream.close()
#Open the file now
if sys.platform.startswith('darwin'):#open in MAC OX
subprocess.call(["open", "noPassPDF.pdf"])

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