0

Using Iron Python I need to first determine if the excel file is already open and then if it is open, access it. if its not open then open it. problem: in my try statement when I try to open the workbook if its already open instead of failing the try it completes it instead and prompts the user to save / cancel the open file in excel. I want it to fail the try if the excel file is already open not prompt the user.

I use the Marshal Interopt lib to access the open file and that works well

UserExcelFile = os.path.join(userdirectory, 'podi.xlsx')    
try:
  workbook = excel.Workbooks.Open(UserExcelFile)
except:
  print "Looks like it was already open"
  return
workbook = excel.ActiveWorkbook
ws = excel.ActiveSheet

If the file is already open "workbook = excel.ActiveWorkbook" works perfect to edit the already open excel file.

2 Answers2

0

I don't think your try except statement is going to catch an exception here. The line below will open the same file again even if it is already open.

workbook = excel.Workbooks.Open(UserExcelFile)

You should check if the file is already open yourself. Suggestions on how it can be done can be found here on stack: Python: Open Excel Workbook using Win32 COM Api

  • Since I cannot upgrade my version of Iron Python to Win32 COM Api, is there a way to make that work with just Microsoft.Office.Interop? This runs inside a simulation program and its got a fixed version of Iron Python. – twistedneck Jun 21 '19 at 07:54
  • Maybe you can try checking if the file was closed before trying to open it again? You can do this by checking if workbook.closed is true or false before trying to open it again. – Aivaras Kazakevičius Jun 21 '19 at 08:44
0

I finally got this working to where it will check using interop if the excel file is already open, if its not, it will open and start.. if it is already open then it just starts editing the open workbook. This is only a big deal for me because its Iron Python and the Win32 COM Api will not work with Iron.

    if ex.Workbooks.Open(UserExcelFile) == True:
        ExtAPI.Log.WriteMessage("excel file already open")
        workbook = excel.ActiveWorkbook
        ex = workbook
        ws = excel.ActiveSheet
    else: 
        workbook = ex.Workbooks.Open(UserExcelFile)
        ws = workbook.Worksheets[1]