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

前端 未结 5 713
萌比男神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
    慢半拍i (楼主)
    2020-12-24 03:01

    Try this one. This function below will return generator contains dict of each row and column.

    from xlrd import open_workbook
    
    for row in parse_xlsx():
        print row # {id: 4, thread_id: 100, forum_id: 3, post_time: 1377000566, votes: 1, post_text: 'here is some text'}
    
    def parse_xlsx():
        workbook = open_workbook('excelsheet.xlsx')
        sheets = workbook.sheet_names()
        active_sheet = workbook.sheet_by_name(sheets[0])
        num_rows = active_sheet.nrows
        num_cols = active_sheet.ncols
        header = [active_sheet.cell_value(0, cell).lower() for cell in range(num_cols)]
        for row_idx in xrange(1, num_rows):
            row_cell = [active_sheet.cell_value(row_idx, col_idx) for col_idx in range(num_cols)]
            yield dict(zip(header, row_cell))
    

提交回复
热议问题