Search code examples
pythonexcelxlrd

how to extract rows from excel file


I have an excel file. How can I extract data so that in python it looks like:

list = [['Igor', '20', 'SSU]'], ['Sergay', '19', 'SSTU'], ['Nadya', '21', 'SSAU']] 

using import xlrd


Solution

  • You can build a list using the following:

    # Import:
    import xlrd 
    
    # Setting Path of File and Initializing List:
    location = ("path of file") 
    list = []
    
    # Opening the Workbook and Defining Which Sheet to Use:
    wb = xlrd.open_workbook(location) 
    sheet = wb.sheet_by_index(0) 
    
    # Starting at Row 0 and Column 0:
    sheet.cell_value(0, 0)
    
    # Iterating Over the Number of Rows and Appending to List:
    for i in range(1, sheet.nrows + 1):
       list.append(sheet.row_values(i))
    

    You could also loop through each of the sheets in the workbook by wrapping the wb.sheet_by_index in a for loop with the number of sheets. You may also want to run some checks to make sure the row isn't empty.

    Please excuse any errors, my Python dealing with Excel is slightly rusty.