How to close an excel file using terminal or python

11,835

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

Share:
11,835

Related videos on Youtube

user37473
Author by

user37473

Updated on September 18, 2022

Comments

  • user37473
    user37473 almost 2 years

    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.

    • barlop
      barlop almost 9 years
      i'm not sure if this is relevant but maybe a VBA macro is ok for you and maybe it can be called from the command line stackoverflow.com/questions/2050505/…
    • user37473
      user37473 almost 9 years
      Please see the edits. I have excel. That is what I am using currently to look at the file. @barlop I am on Mac OSX. I am not sure whether the link you gave would work for that. Sorry, forgot to include that information above.
  • user37473
    user37473 almost 9 years
    I think this solution is for Windows. I am using Excel on Mac. Please correct me if I am wrong.
  • ParanoidPenguin
    ParanoidPenguin almost 9 years
    Hi @user37473 , I've made an update to include some Mac specific information.