Search code examples
pythonexcelxlrd

Specify filename in python script to open Excel workbook


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

Solution

  • 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