Search code examples
excelpython-2.7listfor-loopxlrd

How to append specific data from excel file into a python list?


I have import an excel file. The excel file has hot 2 rows and 5 columns like this:

Weights 1 5 9 8
Criteria Number 38 89 8 56

excel_file = tkFileDialog.askopenfilename(filetypes=[('excelfile','*.xlsx')],title='Choose a .xlsx file')

n_crit = []
workbook = xlrd.open_workbook(excel_file)
sheet = workbook.sheet_by_index(0)

data = []
for r in range(sheet.nrows):
    sublist = []
    for c in range(sheet.ncols):
        if r == "Weights":
            sublist.append(sheet.cell_value(r,c))
    data.append(sublist)

print data

I want to append to the list data the data inside the excel file. If the first cell in any column is Weights then it will append all numbers in the row of Weights except the first column value (Weights) to the data list as:

data = [[1 5 9 8]]

Solution

  • Try the following:

    import tkFileDialog
    import xlrd
    
    
    excel_file = tkFileDialog.askopenfilename(filetypes=[('excelfile','*.xlsx')],title='Choose a .xlsx file')
    
    workbook = xlrd.open_workbook(excel_file)
    sheet = workbook.sheet_by_index(0)
    
    data = [sheet.row_values(i)[1:] for i in range(sheet.nrows) if sheet.row_values(i)[0]=='Weights']
    
    # [[1.0, 5.0, 9.0, 8.0]]
    

    I hope this helps.