Run Excel from Python, Run Macro WITH Credentials - python

I have a block of code that I have used in the past to touch an excel file, run a macro already saved in the workbook, save and close. For example:
import win32com.client
import os
import os.path
file = 'myworkbook.xlsm'
path = 'C:/PATH/'
macro = 'mymacro'
filename = os.path.join(path, file)
xlApp = win32com.client.Dispatch("Excel.Application")
wkbk = xlApp.Workbooks.Open(filename)
runMacro = wkbk.Name + '!' + macro
xlApp.Run(runMacro)
wkbk.Save()
wkbk.Close(1)
xlApp.Quit()
xlApp = None
However, I would now like to use this on a macro that refreshes a data connection, and thus prompts for the password for the SQL database in question. When I try to run this, without worrying about the credentials, I get this error:
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office
Excel', u"Cannot run the macro 'MYMACRO'. The
macro may not be available in this workbook or all macros may be
disabled.", u'C:\Program Files (x86)\Microsoft
Office\Office12\1033\XLMAIN11.CHM', 0, -2146827284), None)
Is there a way to make this work---i.e. to pass the required credentials from python to excel so that the macro can run?

Related

Why am I getting 'Open method of Workbooks class failed' error when trying to open Excel file using pywin32?

So, I am using openpyxl and pandas to open an excel file, and write in data. Then, I'm attempting to use pywin32 to open the same file and run a macro to parse the data. But, I'm getting this error when attempting to open the file with pywin32:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)
This is the code I'm using with pywin32:
if os.path.exists(self.excel_parser_location):
# print "Opening Telematics_Messages_Parser.xlsm in Excel"
xl = client.Dispatch("Excel.Application")
xl.Application.visible = True
wb = xl.Workbooks.Open(os.path.abspath(self.excel_parser_location), ReadOnly=1)
And this is the code I'm using to write in the data before using pywin32:
if os.path.exists(csv_path):
data = pd.read_csv(csv_path, error_bad_lines=False)
book = openpyxl.load_workbook(self.excel_parser_location, keep_vba=True)
writer = pd.ExcelWriter(self.excel_parser_location)
writer.book = book
data.to_excel(writer, sheet_name='2 RawData', index=False)
# print 'Writing new data'
book.remove(book['2 RawData'])
# print 'Removing blank sheet'
book_sheet = book['2 RawData1']
book_sheet.title = '2 RawData'
# print 'Renaming sheet'
writer.save()
writer.close()
I've had a similar issue in the past that I resolved by using an older version of pywin32, but that isn't working now. I'm using pywin32 version 223.
Sometimes this error occured when path to file is too long. So you should try this code with file with shorter path

How can I write only the file name instead of writing the entire path?

I'm trying to use os.chdir so I can only write the name of the file within the directory(Table1.xlsx) instead of writing the entire path(r"C:\Users\crist\word_automation\Summary_template\Table1.xlsx"), but this code seems to not be working.
from win32com import client
import os
os.chdir(r"C:\Users\crist\word_automation\Summary_template")
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open('Table1.docx')
book = excel.Workbooks.Open('Table1.xlsx')
sheet = book.Worksheets(1)
sheet.Range("A1:D5").Copy()
wdRange = doc.Content
wdRange.Collapse(0)
wdRange.PasteExcelTable(False, True, False)
os.remove('Table2.xlsx')
book.SaveAs('Table2.xlsx')
book.Close()
excel.Quit()
doc.SaveAs('TableOne.docx')
doc.Close()
word.Quit()
I get this error:
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find Table1.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)
Try To Make Variable with the path like:
path = "desired/path/to/project"
and then whenever you want to interact with saving or loading files:
book.SaveAs(f'{path}/filename')

Python win32com convert from xlsx/xls to xlsm?

I have seen many responses for win32com on how to convert from xlsm to xlsx or xls, but I am trying to do the exact opposite. I tried to mimic the code used to convert xlsm to xlsx but I get an error message. The code I'm using is:
import win32com.client as win32
from win32com import client
from shutil import copyfile
xlApp = client.gencache.EnsureDispatch('Excel.Application')
if file_original[-1] == "x" or file_original[-1] == "s": # If it is xlsx or xls
file_temp = copyfile(file_orig, str(main_folder) + "\\mainfile_duplicated_nomacro.xlsx")
books_temp = xlApp.Workbooks.Open(str(main_folder) + "\\mainfile_duplicated_nomacro.xlsx")
books_temp.SaveAs(Filename = "\\mainfile_duplicated.xlsm" , FileFormat = 52)
books_temp.Close(True)
elif anl_orig[-1] == "m": # If it is xlsm
file_dup = copyfile(file_orig, str(main_folder) + "\\mainfile_duplicated.xlsm")
When I save books_temp, I use FileFormat = 52, which is something I got from here. The error message I get is:
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel',
"Microsoft Excel cannot access the file 'C:\EDF0B000'. There are
several possible reasons:\n\n• The file name or path does not
exist.\n• The file is being used by another program.\n• The workbook
you are trying to save has the same name as a currently open
workbook.", 'xlmain11.chm', 0, -2146827284), None)
Where am I going wrong?

How do I get an XLA add in into excel through python using win32com.client?

I have to run macros in an excel file, which can be done through python win32. But I have a third party excel add-in required to run the macros. The excel which is opened through win32 does not have the add-ins linked. The add-in is in a XLA file format.
This is my code
new_file_path = path to excel_file.xlsm
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
refprop_path = path to XLA file
xl.Workbooks.Open(refprop_path)
xl.AddIns.Add(refprop_path)
xl.Workbooks.Open(new_file_path)
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
for i in range(0, 3):
xl.Application.Run("iter1.xlsm!Sheet1.temp_const_gauge")
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
xl.Application.Save()
xl.Application.Quit()
The add-in as not added and I get an error.
xl.AddIns.Add(refprop_path).Installed = True
File "<COMObject <unknown>>", line 3, in Add
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'Add method of AddIns class failed', u'xlmain11.chm', 0, -2146827284), None)
I did not have to explicitly write a line to add the add in. I removed that line and the problem was solved.
Working code:
new_file_path = path to excel_file.xlsm
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
refprop_path = path to XLA file
xl.Workbooks.Open(refprop_path)
xl.Workbooks.Open(new_file_path)
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
for i in range(0, 3):
xl.Application.Run("iter1.xlsm!Sheet1.temp_const_gauge")
xl.Application.Run("iter1.xlsm!Sheet1.copy_data")
xl.Application.Save()
xl.Application.Quit()
I seems that the add-in in the XLA file can be used just by keeping it open in the background.

tomcat/CGI and python3 fails to use win32com to open Excel file

I have a PY3 script that uses Win32COM to instantiate a new Excel instance and attempt to open an existing .xlsx file - boiled down, this fails when called via Tomcat/CGI on Windows:
sys.stdout.write("Content-Type: text/html\n\n")
excel = DispatchEx('Excel.Application')
dir = r'C:\temp'
s = 'test.xlsx'
sfile = os.path.join(dir, s)
try:
wbS = excel.Workbooks.Open(sfile)
except pythoncom.com_error as error:
print("exception details: {0}".format(error))
exit(1)
Action fails with:
exception details: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Microsoft Excel cannot access the file 'C:\\temp\\test.xlsx'. There are several possible reasons:\n\n• The file name or path does not exist.\n• The file is being used by another program.\n• The workbook you are trying to save has the same name as a currently open workbook.", 'xlmain11.chm', 0, -2146827284), None)
Fails when Tomcat runs either as Administrator or local account, both having Full Control access to the existing file. EnsureDispatch, Dispatch and DispatchEX do not yield success. No other application is accessing/locking the file. Running from within a cmd succeeds, suggesting that something is lost at the CGI level.
(Using COM allows for copying of worksheets between workbooks and other activities not supported by XLSWriter, et.al.)

Categories