14

I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?

warren
  • 32,620
  • 21
  • 85
  • 124
Ray
  • 187,153
  • 97
  • 222
  • 204

7 Answers7

12

While the Popen answers are reasonable for the general case, I would recommend win32api for this specific case, if you want to do something useful with it:

It goes something like this:

from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls')
xl.Visible = True    # optional: if you want to see the spreadsheet

Taken from a mailing list post but there are plenty of examples around.

gene_wood
  • 1,960
  • 4
  • 26
  • 39
Ali Afshar
  • 40,967
  • 12
  • 95
  • 109
8

or

os.system("start excel.exe <path/to/file>")

(presuming it's in the path, and you're on windows)

and also on Windows, just start <filename> works, too - if it's an associated extension already (as xls would be)

warren
  • 32,620
  • 21
  • 85
  • 124
  • 3
    Note that on Windows you will see the cmd window quickly open and close if you `os.system()`. IMHO it's better to use `os.startfile()`. – thdoan Dec 30 '14 at 04:06
7

I like popen2 for the ability to monitor the process.

excelProcess = popen2.Popen4("start excel %s" % (excelFile))
status = excelProcess.wait()

https://docs.python.org/2/library/popen2.html

EDIT: be aware that calling wait() will block until the process returns. Depending on your script, this may not be your desired behavior.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
crftr
  • 8,488
  • 4
  • 34
  • 44
7

The subprocess module intends to replace several other, older modules and functions, such as:

  • os.system
  • os.spawn*
  • os.popen*
  • popen2.*
  • commands.*

.

import subprocess

process_one = subprocess.Popen(['gqview', '/home/toto/my_images'])

print process_one.pid
Oli
  • 15,345
  • 8
  • 30
  • 36
3

As others have stated, I would suggest os.system. In case anyone is looking for a Mac-compatible solution, here is an example:

import os
os.system("open /Applications/Safari.app")
codedude
  • 71
  • 1
0

os.system("open file.xls")

Marko
  • 30,263
  • 18
  • 74
  • 108
  • Probably works on NeXTstep too. But certainly not Windows or UNIX. Given that the question asks about Excel, I'd assume OS X or Windows. – ephemient Oct 29 '08 at 17:45
0

I like os.startfile("path to file") as it opens the file as if you've double clicked to open.

I found that with os.system("start excel filename") it opened it like a file opened from the web and you had to enable editing.

microbenny
  • 33
  • 7