Mac – How to close an excel file using terminal or python

macmicrosoft-excel-2011terminal

I am using XlsxWriter to create an Excel file using a Python script.

When I re-run the script to update the file with new information, which I need to do often, I have to manually close the Excel file and reopen it to look at the new version of the spreadsheet.

Is there a way to automate this process: Close the excel file (not the application) using a terminal command and then re-open it.

I know how to open it, but don't know how to close a file.

Best Answer

Looking at a post over on Stack Overflow, the answer was that the Workbook COM contains within it a Close() method. The code snippet from the mentioned post:

xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('New Workbook.xlsx')
# do some stuff
wb.Close(True) # save the workbook

Here's the necessary syntax rules from the Microsoft site:

expression .Close(SaveChanges, Filename, RouteWorkbook)
expression A variable that represents a Workbook object.

When it comes to OSX, apparently you need to use appscript

With some looking, I'm not overly familiar with appscript, you should be able to get to do what you are looking for by doing something like:

tell application "Microsoft Excel"
   close workbook 1 saving no
end tell

Finally, here is the documentation for the appscript package for Python:

https://pypi.python.org/pypi/appscript

Related Question