Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a Workbook with XLWINGS without making it visible

Tags:

I am starting to use XLWings (not that I like Excel, at all, but it is something I HAVE TO do). The thing is that I cannot find the way to make Python open a Workbook without showing it.

It seems the constructor for Workbooks in the old XLWings 0.6.4 was xlwings.Workbook, and one of the arguments was a flag 'app_visible' (see http://docs.xlwings.org/en/v0.6.4/api.html).

However, in the new v0.9.2 Workbook has been replaced by Book, and Book does not have any such flag (http://docs.xlwings.org/en/stable/api.html). The App object does have it, and I thought that was the way to go. So I coded:

import xlwings as xw  app = xw.App(visible=False) filename = os.path.join(PATH_EXCEL_SAMPLES, r"rangosConDatos_sample01.xls") book = xw.Book(filename) # Do stuff with the info in the book book.close()  # Ya puedo cerrar el libro. app.kill() 

But, regretably, when

book = xw.Book(filename) 

is executed the 'visible' attribute of app suddenly becomes True, and the book is shown. I do not know if this is a desired feature or an unexpected behaviour. Anyway, any ideas how should I do it?

like image 512
zeycus Avatar asked Aug 17 '16 11:08

zeycus


People also ask

Which is better Openpyxl or Xlwings?

xlwings is the better choice if you want to split the design and code work. XlsxWriter/OpenPyxl is the better choice if it needs to be scalable and run on a server. If you need to generate PDF files at high speed, check out ReportLab.

Does Xlwings require Excel?

Prerequisites. xlwings requires an installation of Excel and therefore only works on Windows and macOS.

Does Xlwings work with XLSM?

Yes, it does indeed work with . xlsm files.

What can you do with Xlwings?

Xlwings can be used to insert data in an Excel file similarly that it reads from an Excel file. Data can be provided as a list or a single input to a certain cell or a selection of cells.


2 Answers

Here is my working code fragment:

    import xlwings      excel_app = xlwings.App(visible=False)     excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')     excel_book.save()     excel_book.close()     excel_app.quit() 
like image 166
Alexey Korolkov Avatar answered Sep 22 '22 09:09

Alexey Korolkov


Since version 0.24.3, where with xw.App is implemented, the idiomatic way is:

import xlwings as xw  with xw.App(visible=False) as app:     book = xw.Book("test.xlsx")      # Do some stuff e.g.     book.sheets[0]["A1"].value = 12345      book.save("test.xlsx")     book.close() 

The advantage of this is that there won't be any hidden excel processes left over in the background, if you use a hidden instance and your code fails.

like image 42
mouwsy Avatar answered Sep 20 '22 09:09

mouwsy