1. 程式人生 > 實用技巧 >python-excel讀寫封裝

python-excel讀寫封裝

import os
from openpyxl import load_workbook


import logging
from utils import project_path


class DoExcel:
    def __init__(self, file_name, sheet_name):
        self.file_name = file_name
        self.sheet_name = sheet_name

    def get_data(self):  # 獲取測試資料
        wb = load_workbook(self.file_name)  # 開啟工作簿
        sheet = wb[self.sheet_name]  # 測試用例的表單  也可固定這個表單   使傳引數量減少

        test_data = []
        for i in range(2, sheet.max_row + 1):  # sheet.max_row    sheet.max_column獲取表單最大行   列
            sub_data = {}
            sub_data['id'] = sheet.cell(i, 1).value  #
            sub_data['user'] = sheet.cell(i, 2).value
            sub_data['pwd'] = sheet.cell(i, 3).value
            sub_data['status'] = sheet.cell(i, 4).value
            sub_data['cookie'] = sheet.cell(i, 5).value
            test_data.append(sub_data)

        return test_data



    def write_back(self, sheet_name, row, status, cookie):  # 寫回資料到Excel
        wb = load_workbook(self.file_name)
        sheet = wb[sheet_name]
        print("正在寫入status")
        sheet.cell(row, 4).value = status
        print("正在寫入cookie")
        sheet.cell(row, 5).value = cookie
        wb.save(self.file_name)


if __name__ == '__main__':



    # DoExcel(project_path.google_user_path, "Sheet1").write_back("Sheet1",2,'1111','2222')
    res = DoExcel(project_path.google_user_path, "Sheet1").get_data()
    print(res)