I am trying to open an excel which is connected to BBG and refresh values.
To open an instance of excel and load bloomberg addins, I used a solution from the attached link a while ago
Python using win32com wont update excel sheet with needed Add-ins
The solution worked fine for me till yday when for some reason xlapp.RegisterXLL('C:/blp/API/Office Tools/bofaddin.dll') is giving me trouble. i.e. not loading and crashing my codes.
Anyone has any ideas whats happening?
Codes are below if anyone interested
import os, os.path
import win32com.client
xlapp = win32com.client.DispatchEx("Excel.Application")
xlapp.RegisterXLL('C:/blp/API/Office Tools/bofaddin.dll')
xlapp.Workbooks.Open('C:\\blp\\API\\Office Tools\\BloombergUI.xla')
wb = xlapp.Workbooks.Open(filepath,None,False)
xlapp.Visible = True
wb_addin = ('C:/blp/API/Office Tools/bofaddin.dll')
wb.RefreshAll()
Try importing time and putting time.sleep(2) after each command. I found the Bloomberg links sometimes need a second to update.
xlapp = win32com.client.DispatchEx("Excel.Application")
time.sleep(2)
xlapp.RegisterXLL('C:/blp/API/Office Tools/bofaddin.dll')
time.sleep(2)
xlapp.Workbooks.Open('C:\\blp\\API\\Office Tools\\BloombergUI.xla')
time.sleep(2)
wb = xlapp.Workbooks.Open(filepath,None,False)
xlapp.Visible = True
wb_addin = ('C:/blp/API/Office Tools/bofaddin.dll')
Related
I want to open and edit an excel workbook. However, when I run the following, it always create a new book (Book1) which I don't want.
import xlwings as xw
mypath= #path
app= xw.App()
wb=app.books.open(mypath)
After running, there will always be an unnecessary new Book1 created. Is there anyway to make it tidier?
I tried replacing app=xw.App() with app=xw.App(add_book=False), but it shows error below:
raise XlwingsError("Couldn't find any active App!")
xlwings.XlwingsError: Couldn't find any active App!
I also tried removing the line app=xw.App() and directly open the book with
wb=xw.books.open(mypath)
If I already have an excel file opened, then this worked as I wish, opened the book with any new book created. But if there is no other excel file opened, then the same error as above is raised.
Also tried the following from previous questions. https://stackoverflow.com/questions/11018237/open-excel-application-without-new-workbook
import xlwings as xw
mypath= #path
app= xw.App()
app.ActiveWorkbook.Close(False);
app.visible = True;
wb=app.books.open(mypath)
Error occured
app.ActiveWorkbook.Close(False);
AttributeError: 'App' object has no attribute 'ActiveWorkbook'
This seems to be a very simple question, please bear me since I am very new to Python (and xlwings) and this is my first time asking questions here.
I like to use a context manager since it cleans up nicely at close.
import xlwings as xw
workbook = 'Book1.xlsx'
with xw.App() as app:
wb = xw.Book(workbook)
ws = wb.sheets('Sheet1')
...
wb.save(workbook) # needed only if data is written to the workbook
wb.close()
##----------------------------##
##----------------------------##
import xlwings as xw
workbook = 'yourExcelFile.xlsm'
with xw.App(visible=False, add_book=False) as app:
wb = xw.Book(workbook)
ws = wb.sheets('Sheet1')
# ...
print(ws.range('A1').value)
wb.save(workbook) # <-- Needed only where sheet data changed
wb.app.quit()
I would like to automatically refresh my excel file which is connected to Analysis service without asking me to enter password each time i run the code or a way to pass the password without manual entry.
Currently the code which M using is
import win32com.client
import pandas as pd
# Start an instance of Excel
xlapp = win32com.client.DispatchEx("Excel.Application")
# Open the workbook in said instance of Excel
wb = xlapp.workbooks.open(r"<excel path>")
# Optional, e.g. if you want to debug
# xlapp.Visible = True
# Refresh all data connections.
wb.RefreshAll()
wb.Save()
file_name = 'sample.xlsx'
sheet = 'Sheet1'
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(50))
# Quit
xlapp.Quit()
How to automatically refresh the Excel file without asking me password or an alternative to send the password.
Thanks for you answer!
I am trying to run a VBA Macro in an xlsm workbook using python 3.7 in Spyder. This workbook has two worksheets.
The code that I have currently runs and saves the new file with no problems, however it is not triggering the VBA like it should.
I know this macro works because if I manually click the button in Excel, it works just fine.
Could someone assist with this? I checked the Macro Settings under the Trust Center and all macros are enabled so I do not think it is a permissions issue, however I am not an admin on this pc.
The code is below:
import os
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open("Z:\FolderName\FolderName2\FileName.xlsm")
xl.Application.Run("MacroName")
wb.SaveAs("Z:\FolderName\FolderName2\FileName1.xlsm")
wb.Close()
xl.Quit()
This can be done easily through xlwings. Once I switched to that library then I was able to quickly get this script working.
First make sure you have your All.xlsm file in your current working or in your User/Documents(Sometimes it working from yourDocuments directory and sometimes not, so better to have in both)
pass your macro name along with the file name that contains the macro you can make change to Parameters like ReadOnly or Savechanges according to your requirement
And be make sure to deleta xl object after each run
import win32com.client
xl =win32com.client.dynamic.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename = XYZ.xls, ReadOnly= 1)
xl.Application.Run('All.xlsm!yourmacroname')
xl.Workbooks(1).Close(SaveChanges=1)
xl.Application.Quit()
del xl
Running Excel Macro from Python
To Run a Excel Marcro from python, You don't need almost nothing. Below a script that does the job. The advantage of Updating data from a macro inside Excel is that you immediatly see the result. You don't have to save or close the workbook first. I use this methode to update real-time stock quotes. It is fast and stable.
This is just an example, but you can do anything with macros inside Excel.
from os import system, path
import win32com.client as win32
from time import sleep
def isWorkbookOpen(xlPath, xlFileName):
SeachXl = xlPath + "~$" + xlFileName
if path.exists(SeachXl):
return True
else:
return False
def xlRunMacro(macroLink):
PathFile = macroLink[0]
xlMacro = macroLink[1]
isLinkReady = False
# Create the link with the open existing workbook
win32.pythoncom.CoInitialize()
xl = win32.Dispatch("Excel.Application")
try:
wb = win32.GetObject(PathFile)
isLinkReady = True
except:
NoteToAdd = 'Can not create the link with ' + PathFile
print(NoteToAdd)
if isLinkReady:
# If the link with the workbook exist, then run the Excel macro
try:
xl.Application.Run(xlMacro)
except:
NoteToAdd = 'Running Excel Macro ' + xlMacro + ' failed !!!'
print(NoteToAdd)
del xl
def mainProgam(macroSettings):
FullMacroLink = []
PathFile = macroSettings[0] + macroSettings[1]
FullMacroLink.append(PathFile)
FullModuleSubrout = macroSettings[1] + '!' + macroSettings[2] + '.' + macroSettings[3]
FullMacroLink.append(FullModuleSubrout)
if isWorkbookOpen(macroSettings[0], macroSettings[1]) == False:
# If the workbook is not open, Open workbook first.
system(f'start excel.exe "{PathFile}"')
# Give some time to start up Excel
sleep(2)
xlRunMacro(FullMacroLink)
def main():
macroSettings = []
# The settings below will execute the macro example
xlPath = r'C:\test\\' # Change add your needs
macroSettings.append(xlPath)
workbookName = 'Example.xlsm' # Change add your needs
macroSettings.append(workbookName)
xlModule = "Updates" # Change add your needs
macroSettings.append(xlModule)
xlSubroutine = "UpdateCurrentTime" # Change add your needs
macroSettings.append(xlSubroutine)
mainProgam(macroSettings)
if __name__ == "__main__":
main()
exit()
VBA Excel Macro
Option Explicit
Sub UpdateCurrentTime()
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("Current-Time")
With sht
sht.Cells(2, 1).Value = Format(Now(), "hh:mm:ss")
End With
End Sub
You can use it also as a dynamic module too. Save the module above as RunExcelMacro.py in Your python project. After just use the following lines:
from RunExcelMacro import mainProgam
mainProgram(macroSettings)
It will do the job, succes ...
You need to reference the module name as well
Example here my vba code under Module1
Option Explicit
Public Sub Example()
MsgBox "Hello 0m3r"
End Sub
and here is my python
from win32com.client import Dispatch
def run_excel_macro():
try:
excel = Dispatch("Excel.Application")
excel.Visible = True
workbook = excel.Workbooks.Open(
r"D:\Documents\Book1.xlsm")
workbook.Application.Run("Module1.Example")
workbook.SaveAs(r"D:\Documents\Book5.xlsm")
excel.Quit()
except IOError:
print("Error")
if __name__ == "__main__":
run_excel_macro()
I have a few excel process that are run in Macros. I have tried to automate the jobs and want to use python to:
Open excel
Add any com32 add-ins
Run the macro
When the macro is complete close the instance of excel
I have sample code below - I find that the code is sometimes unstable. It doesnt always add the add-in and I dont know when to close the excel object, i.e. if the macro runs for some time, the python script doesnt know to wait.
Are there better ways for achieving this? I would like to move more macros into python, but there are many users of the excel scripts so this is a longer term goal.
import win32com.client
import os
import traceback
DIRECTORY = '*'
FILE = '*.xlsm'
MACRO = '*'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
xlApp.RegisterXLL('*.xll')
wb = xlApp.Workbooks.Open(Filename=path)
xlApp.Application.Run(MACRO)
wb.Save()
wb.Close()
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
I have an Excel file that I run a Python script on. The Excel file has external data connections that need to be refreshed before the Python script is run. The functionality I'm referring to is here:
I'm using Python 2.7 and am relying on Pandas for most of the Excel data parsing.
CalculateUntilAsyncQueriesDone() will hold the program and wait until the refresh has completed.
xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
wb.Save()
xlapp.Quit()
If you're on windows, and I believe you are given the screenshot, you can use the win32com module. It will allow you - from python - to open up Excel, load a workbook, refresh all data connections and then quit. The syntax ends up being pretty close to VBA.
I suggest you install pypiwin32 via pip (pip install pypiwin32).
import win32com.client
# Start an instance of Excel
xlapp = win32com.client.DispatchEx("Excel.Application")
# Open the workbook in said instance of Excel
wb = xlapp.workbooks.open(<path_to_excel_workbook>)
# Optional, e.g. if you want to debug
# xlapp.Visible = True
# Refresh all data connections.
wb.RefreshAll()
wb.Save()
# Quit
xlapp.Quit()
Adding this as an answer since this is the first Google link - the code in the first answer worked but has incorrect capitalization, it should be:
import win32com.client
import time
xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
time.sleep(5)
wb.Save()
xlapp.Quit()
A small note, but important one. All the codes above are correct, but it will raise the issue with permission Err 13 because the file is only being saved, not closed as well.
add wb.Close() after save, otherwise the openned Excel will remain in the background app, and if you work with 500 of those, you might get a bit into troubles
Adding on top of what everyone else has said, I kept getting the save dialog again when the code got to the Quit line. I set the DisplayAlerts flag to false and it fixed my issue. I didn't need the sleep timer either. This is what worked for me:
xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
xlapp.DisplayAlerts = False
wb.Save()
xlapp.Quit()
Adding another slightly changed answer as I was stumped by this and none of the solutions were working. What worked for me was enabling Xlsx.DisplayAlerts = True and Xlsx.Visible = True, then at end saving the book with book.Save() and also closing with save: book.Close(SaveChanges=True).
It's a bit cumbersome with Excel opening and closing every time (I am iterating through many excel files), but it works so thats good.
import win32com.client as win32
import pythoncom
def open_close_as_excel(file_path):
try:
pythoncom.CoInitialize()
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = True
Xlsx.Visible = True
book = Xlsx.Workbooks.Open(file_path)
book.RefreshAll()
Xlsx.CalculateUntilAsyncQueriesDone()
book.Save()
book.Close(SaveChanges=True)
Xlsx.Quit()
pythoncom.CoUninitialize()
book = None
Xlsx = None
del book
del Xlsx
print("-- Opened/Closed as Excel --")
except Exception as e:
print(e)
finally:
# RELEASES RESOURCES
book = None
Xlsx = None