1. 程式人生 > >python讀excel資料

python讀excel資料

1.環境準備

安裝:pip install xlrd

 

2.基本操作

(1)開啟excel表格,操作表格

3.excel存放資料

(1)在excel中存放資料,第一行為標題,也就是對應字典裡面的key值,如:username,password

(2)如果excel資料中有純數字的需要設定為文字格式

 

4.封裝讀取方法

(1)程式碼:

# coding:utf-8
import xlrd
# 封裝讀取方法
class ExcelUtil:
    def __init__(self, excel_path, sheet_name):
        self.data = xlrd.open_workbook(excel_path)
        self.table = self.data.sheet_by_name(sheet_name)

        # 獲取第一行作為key值
        self.keys = self.table.row_values(0)

        # 獲取總行數
        self.rowNum = self.table.nrows

        # 獲取總列數
        self.colNum = self.table.ncols

    def dict_data(self):
        if self.rowNum <= 1:
            print("總行數小於1")
        else:
            r = []  # 存放讀取資料
            j = 1
            for i in range(self.rowNum - 1):
                s = {}  # 存放每一行的鍵值對

                # 從第二行取對應的value值
                values = self.table.row_values(j)

                for x in range(self.colNum):
                    s[self.keys[x]] = values[x]
                r.append(s)
                j += 1
            return r


if __name__ == '__main__':
    instance_excel = ExcelUtil("suner.xlsx", "user_info")
    d = instance_excel.dict_data()
    print(d)

(2)結果:

 [{'username': 'admin', 'password': '123456'}, {'username': 'suner', 'password': '123456'}]