天天看點

python3:從excel中讀取資料,并以字典組成的清單傳回

python3:從excel中讀取資料,并以字典組成的清單傳回
#!/usr/bin/env python
# coding: utf-8

import xlrd


def read_xlsx(path, sheet):
    # book = xlrd.open_workbook(path)   # 打開excel表
    with xlrd.open_workbook(path, 'rb') as book:
        table = book.sheet_by_name(sheet)  # 找到sheet頁

        # 擷取總行數總列數
        row_num = table.nrows
        col_num = table.ncols

        xlsx_list = []
        key = table.row_values(0)  # 這是第一行資料,傳回一個清單,作為字典的key值
        if row_num <= 1:
            print('excel為空')
        else:
            j = 1  # 從第二行開始擷取值
            for i in range(row_num-1):  # 有多少行,讀多少次
                xlsx_dict = {}
                values = table.row_values(j)
                for x in range(col_num):  # 有多少列,指派多少次
                    # 把key值對應的value指派給key,每行循環一次
                    xlsx_dict[key[x]] = values[x]
                j = j + 1
                # 把字典添加到清單中
                xlsx_list.append(xlsx_dict)
            return xlsx_list


if __name__ == '__main__':
    read_xlsx0 = read_xlsx(path='..\\test_file\\send_values.xlsx', sheet='user_pwd')
    print(read_xlsx0)
           
python3:從excel中讀取資料,并以字典組成的清單傳回

繼續閱讀