0

I'd like to know if it is possible to write a python script which will make Windows 7 open a non-xls file with Excel, such as:

file_path = somefile
open_file_with_excel(filepath)

The script should find Excel application, because Excel's installation directory is not same in every PC.

tshepang
  • 12,111
  • 21
  • 91
  • 136
alwbtc
  • 28,057
  • 62
  • 134
  • 188
  • 2
    I know some of you have itchy fingers to close questions, at least let me get an answer for it first. – alwbtc Aug 03 '13 at 09:31

2 Answers2

3

I believe so:

import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
xl.Visible = 1
xl.Workbooks.open('filename')

Importing pywin32: How to install pywin32 module in windows 7

Advanced python+excel: http://oreilly.com/catalog/pythonwin32/chapter/ch12.html

Community
  • 1
  • 1
RowanC
  • 1,611
  • 10
  • 16
  • win32com very is useful if you need to actually manipulate the contents of a file within excel but under python control - I have however had a couple of IDEs and other packages moan about it being installed as it seems it can cause them some problems. – Steve Barnes Aug 03 '13 at 10:12
1

If excel is on your path than just subprocess.Popen([r'path_to_file']) will do the job. If the file is not associated with excel then you would need to use:

subprocess.Popen(['excel', r'path_to_file'])

or if excel is not on the path:

subprocess.Popen([r'path_to_excel', r'path_to_file'])

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • But the file is not an .xls file – alwbtc Aug 03 '13 at 09:35
  • 1
    @alwbtc add file extension to "open with" and make exel default. – eri Aug 03 '13 at 09:45
  • @eri No, i'm not going to do that, because it is a text file. – alwbtc Aug 03 '13 at 14:45
  • @alwbtc save it as csv – eri Aug 03 '13 at 16:27
  • @Steve Barnes what does `r` mean here? and how do I write it if `path_to_file` is a variable, such as `path_to_file="C:\myfile"` then `subprocess.Popen(['excel', r path_to_file])`? – alwbtc Aug 04 '13 at 14:11
  • Path to file is the complete path to the file including the drive, directory, filename & extension e.g. `C:\mydir\Fred.txt` - this needs to be stored in a string and the `\`s will have special meaning unless escaped by either doubling all the `\`s or by prefixing the string with the letter `r` - the string can be stored in a variable e.g. `my_var = r'C:\mydir\Fred.txt'` and then used. – Steve Barnes Aug 04 '13 at 18:22