Specify filename in python script to open Excel workbook

1.9k views Asked by At

this is a really dumb question, but Im trying to learn python and I got stuck on example with reading Excel files using xlrd. I found this script online but I cant figure out where am I supposed to fill my filename to get it open.

from future import print_function
from os.path import join, dirname, abspath, isfile
from collections import Counter
import xlrd
from xlrd.sheet import ctype_text   

def get_excel_sheet_object(fname, idx=0): if not isfile(fname): print ('File doesn't exist: ', fname) # Open the workbook and 1st sheet xl_workbook = xlrd.open_workbook(fname) xl_sheet = xl_workbook.sheet_by_index(0) print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)

return xl_sheetsdf
2

There are 2 answers

3
Antoine Gaia On BEST ANSWER

You can enter the filename :

  • When you call the function

    get_excel_sheet_object("myfile.xlsx")

           OR
    

    fname = "myfile.xlsx"

    get_excel_sheet_object(fname)

  • Raw in your program :

    def get_excel_sheet_object(idx=0):
    
          fname = "myfile.xlsx"
    
          if not isfile(fname):
             print ("File doesn't exist: ", fname)
          # Open the workbook and 1st sheet
          xl_workbook = xlrd.open_workbook(fname)
          xl_sheet = xl_workbook.sheet_by_index(0)
          print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)
    
          return xl_sheet      
    
0
harshil9968 On
from future import print_function
from os.path import join, dirname, abspath, isfile
from collections import Counter
import xlrd
from xlrd.sheet import ctype_text   


def get_excel_sheet_object(fname, idx=0):
    if not isfile(fname):
        print ('File doesn't exist: ', fname)
            # Open the workbook and 1st sheet
    xl_workbook = xlrd.open_workbook(fname)
    xl_sheet = xl_workbook.sheet_by_index(0)
    print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)

    return xl_sheet

xl_sheet_obj = get_excel_sheet_object('FILE_NAME_HERE')

Do anything you want with xl_sheet_obj after that this object is the excel sheet object.