Search code examples
pythonexcelxlwings

How to open an existing workbook without creating an new book?


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.


Solution

  • 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()
    

    ##----------------------------##
    xlwings run


    ##----------------------------##

    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()