I am trying to open an excel file with Python to display the data that contented in it, just like we double click it with mouse.
I've search for a while, but seems all the pages are talking about how to read and write an excel file with code, rather than display the content to the user.
So, is there any solution for my problem?
Thanks a lot.
Just to complement wnnmaw's answer, subprocess.popen supports context management and the 'with' operator, which provides a nice, clean, Pythonic way to handle the opening and closing of the file. Basically, there's no need to explicitly close the file with this approach.
The 'with' statement will automatically handle the opening and closing for you, and it's nice and easy to read. The one caveat you must bear in mind is that this is only good for one file at a time. If your function is going to deal with multiple files at once you're better off handling the open/close manually.
If you just want to pass control over to Excel (relying on the end-user to close the file in Excel when finished), see the first part of wnnmaw's answer.
To simply open a file in its default application, you can use
This will open the file in whatever application is associated with the file extension.
There are some drawbacks however, so if you want to do some more advanced handling of the file (such as closing it later), you need a more advanced approach. You can try the solution to my question here which shows how to use
subprocess.popen()
to keep track of the file, and then close it. Here's the general idea:This retains the file you opened as the
doc
object so that it can be easily closed later