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.
Related
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
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!")
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")
So I have this code that I got from here:
How to open a password protected excel file using python?
from xlrd import *
import win32com.client
import csv
import sys
xlApp = win32com.client.Dispatch('Excel.Application')
print('Excel Library Version:', xlApp.Version)
xlwb = xlApp.Workbooks.Open(r'Y:\Production\Production Planning\Production Thruput\% of Completion.xlsm', False, True, None, 'pass2016')
However, it's not working for me. I do not get an error, and the screen even shows the downloading dialog box (screenshot shown below) like if it's about to open my file... and then nothing. What am I doing wrong? I've been researching this for 2 hours and can't seem to find any answers that work for me
I'm developing a Python package to communicate with an API. In order not to hard code the username and password I would like to read the credentials from a JSON file loacated in a 'conf' directory. So if no username and pasword are given it tries to load the credentials from the file:
def __init__(self, user=None, pswd=None):
""" Illustrate method-level docstring."""
if pswd is None:
try:
with open('conf/credentials.json') as data_file:
data = json.load(data_file)
user = data['user']
pswd = data['password']
print('You will log in with user', user)
except IOError:
print("Could not read file: credentials.json. Please Instantiate object with your username and password")
This solution works fine when executing the code in the same directory, but once the package is installed the system doesn't find the file:
Could not read file: credentials.json. Please Instantiate object with
your username and password
How can I overcome this problem? Is it possible to refer to the installation path? I don't want to encrypt the password, I just want to have the credentials in a separate file and add the file in the .gitignore file to prevent sharing this information.
You may try using 'file' which stores filename (with absolute or relative path) and build your path based on this.
You may also store your secret data in other directory (outside of your codebase) like ~/. It may be even better to pass this filename as environmental variable (see os.environ) so users may point to the right file.