XLRD/Python: Reading Excel file into dict with for-loops

前端 未结 5 717
萌比男神i
萌比男神i 2020-12-24 02:19

I\'m looking to read in an Excel workbook with 15 fields and about 2000 rows, and convert each row to a dictionary in Python. I then want to append each dictionary to a list

5条回答
  •  -上瘾入骨i
    2020-12-24 02:55

    This script allow you to transform a excel data to list of dictionnary

    import xlrd
    
    workbook = xlrd.open_workbook('forum.xls')
    workbook = xlrd.open_workbook('forum.xls', on_demand = True)
    worksheet = workbook.sheet_by_index(0)
    first_row = [] # The row where we stock the name of the column
    for col in range(worksheet.ncols):
        first_row.append( worksheet.cell_value(0,col) )
    # tronsform the workbook to a list of dictionnary
    data =[]
    for row in range(1, worksheet.nrows):
        elm = {}
        for col in range(worksheet.ncols):
            elm[first_row[col]]=worksheet.cell_value(row,col)
        data.append(elm)
    print data
    

提交回复
热议问题