0

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 Answers 2

0

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      
    
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but still doesnt work. I have the excel file in the same folder, do I need to specify the full path nevertheles?
well, it said the syntax is wrong. I removed the ' from "don't" and its working now, thanks!
great, so could you accept the answer if it helps you ?
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.