How to open password protected Excel file? - python

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

Related

Retrieve Excel Workbook Connection Properties

I am attempting to grab the "Command Text" from the Connection Property window in an Excel file using python. However, I cannot find the object that contains this information. In the below picture I would like to retrieve the highlighted EXEC sp_FooBar as a string:
I am able to retrieve the Connection names with:
import odbc
import win32com.client
file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.connections:
print(x)
But I'm not sure how to use the <COMObject <unknown>> object further to grab the command text. I'm thinking win32com may have something, but can't seem to crack the code.
You can get the CommandText property from a OLEDBConnectioninstance like this:
import odbc
import win32com.client
file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.Connections:
print(x.OLEDBConnection.CommandText)
xl.Application.Quit()

Simply opening existing excel files with the excel application already open

With excel already open, at the end of some code I am simply trying to open 2 excel files using the following code. However, nothing loads!
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
import datetime
import openpyxl
import time
openPythonQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\PythonQuoteLS.xlsx')
openQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\QuoteLS.xlsm')
If all you want to do is open files in Excel, you can just use the OS library to send the command to the OS to open the file, as Aran-Fey mentioned above.
For your specific files:
import os
# ...
os.system('start excel.exe c:\ls_equity\quote\PythonQuoteLS.xlsx')
os.system('start excel.exe c:\ls_equity\quote\QuoteLS.xlsm')

Connecting from Python to Excel 2016(365) and perform tasks

I have a problem connecting to Excel API in windows 10. I use Office365 and with it Excel2016. My goal is: to download CSV file from a client FTPS Server, merge it with the existing files,perfom some action on it(with pandas) and then load the whole data into excel and do reporting with it... Up to the point of loading it into Excel everything is fine.I managed to do all steps automatically with Python (sorry if my code looks a little cluttered - I am new to Python)
import subprocess
import os
import ftplib
import fnmatch
import sys
from ftplib import FTP_TLS
from win32com.client import Dispatch
import pandas as pd
filematch = '*.csv'
target_dir = 'cannot tell you the path :-) '
def loginftps(servername,user,passwort):
ftps = FTP_TLS(servername)
ftps.login(user=user,passwd=passwort)
ftps.prot_p()
ftps.cwd('/changes to some directory')
for filename in ftps.nlst(filematch):
target_file_name = os.path.join(target_dir,os.path.basename(filename))
with open(target_file_name,'wb') as fhandle:
ftps.retrbinary('RETR %s' %filename, fhandle.write)
def openExcelApplication():
xl = Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden
def mergeallFilestoOneFile():
subprocess.call(['prepareData_executable.bat'])
def deletezerorows():
rohdaten = pd.read_csv("merged.csv",engine="python",index_col=False,encoding='Latin-1',delimiter=";", quoting = 3)
rohdaten = rohdaten.convert_objects(convert_numeric=True)
rohdaten = rohdaten[rohdaten.UN_PY > 0]
del rohdaten['deletes something']
del rohdaten['deletes something']
rohdaten.to_csv('merged_angepasst.csv',index=False,sep=";")
def rohdatenExcelAuswertung():
csvdaten = pd.csv_read("merged.csv")
servername = input("please enter FTPS serveradress:")
user = input("Loginname:")
passwort = input("Password:")
loginftps(servername,user,passwort)
mergeallFilestoOneFile()
deletezerorows()
And here I am stuck somehow,.. I did extensive google research but somehow nobody has ever tried to perform Excel tasks from within Python??
I found this stackoverflow discussion: Opening/running Excel file from python but I somehow cannot figure out where my Excel-Application is stored to run code mentioned in this thread.
What I have is an Excel-Workbook which has a data connection to my CSV file. I want Python to open MS-Excel, refresh data connection and refresh a PivoTable & then save and close the file.
Has anybody here ever tried to to something similar and can provide some code to get me started?
Thanks
A small snippet of code that should work for opening an excel file, updating linked data, saving it, and finally closing it:
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
xl.Workbooks.Open(Filename='C:\\Users\\Xukrao\\Desktop\\workbook.xlsx', UpdateLinks=3)
xl.ActiveWorkbook.Close(SaveChanges=True)
xl.Quit()

Using xlutils xlwt to copy workbook

Is it possible to copy a macros enabled excel workbook? For example, I have:
from xlutils.copy import copy
from xlrd import open_workbook
from tempfile import TemporaryFile
book = open_workbook("book.xlsm")
book_copy = copy(book)
book_copy.save("bookcopy.xlsm")
book_copy.save(TemporaryFile())
However, when I then click on bookcopy.xlsm to open it, I get the following error:
"Excel cannot open the file 'bookcopy.xlsm' because the file format or the file extesion is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
I don't get this error when I save is as "bookcopy.xls", but I need it to be .xlsm. Does anyone have an idea what the problem is?

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