1

I know that we can use subprocess to call and open any file in the explorer. But how do I open a specific sheet in the excel file in Microsoft excel using python?

My program structure is this:

I get the sheet name from user in my python program and I need that excel sheet opened up in excel software.

UPDATE:

My code so far:

import subprocess

subprocess.call("explorer <path-to-my-file>")

but this only opens the file in excel i want a specific sheet in the document to be opened when I call.

thanks in advance

Ram Charran
  • 131
  • 1
  • 3
  • 14
  • please clarify: you want to call Excel from inside Python? Or you are trying to read an xl file into Python? It would be helpful to post your code as well! – patrick Jul 12 '17 at 14:46
  • @patrick He wants to call Excel from Python with the good sheet opened. – Silveris Jul 12 '17 at 14:52
  • is this windows or osx? it's different on each environment... for windows, you'd use the COM interface; for osx, i haven't done it (yet) but it should be an applescript interface of some kind. – Corley Brigman Jul 12 '17 at 14:56
  • @Patrick I want to call excel from python in Windows environment. – Ram Charran Jul 12 '17 at 15:39
  • this should get you started... https://stackoverflow.com/questions/441758/driving-excel-from-python-in-windows ... I don't have a full list of commands, but you can control the view from python.... – Corley Brigman Jul 12 '17 at 16:47

2 Answers2

1

If you want to work with the file in Excel, and use the Python to just open it in Excel, I prefer subprocess.Popen() rather than subprocess.Call().

To open the file in an specific sheet, you should save the workbook open in the selected sheet before opening it in Excel. If your file is a .xlsx file the best Python module is 'openpyxl' (in my opinion of course).

The following code worked fine in my machine (Windows 10, MS Excel 2016 and Python 3.6.3):

import openpyxl
import subprocess
filename = "<Full path to file>"
wsToOpen = "<Worksheet name>"

# Openthe xlsx file in Python
xlsx_file = openpyxl.load_workbook(strCamArq)

# List with all the worksheets in the workbook
lst_worksheets = xlsx_file.get_sheet_names()

# Change the active worksheet in the workbook
xlsx_file._active_sheet_index = lst_worksheets.index(wsToOpen)

# Save the workbook open in the chosen sheet
xlsx_file.save(filename)

#Open the workbook in MS Excel 
subprocess.Popen([filename], shell=True)

Then, the opens the file in MS Excel exactly in the sheet specifyed in 'wsToOpen'

Eduardo Alvim
  • 201
  • 2
  • 4
-1

Use the xlrd library:

import xlrd

for name, sheet_name in zip(filename, sheetnumber):
    book = xlrd.open_workbook(name)
    sheet = book.sheet_by_name(sheet_name)
    for row in range(sheet.nrows):
        for column in range(sheet.ncols):
            print row, column
Funsaized
  • 1,972
  • 4
  • 21
  • 41