Python - 封装操作excel表格类

# coding = utf-8
from tools.read_config import ReadConfig
from openpyxl import load_workbook

case_config = ReadConfig().read_config(section='BUTTON', option='button')
class DoExcel:
    '''操作表格类'''
    def __init__(self, filename):
        self.filename = filename
    def get_data(self):
        '''根据button值判断api是否全部执行,将需要执行的api数据存到final_data'''
        # 1.打开excel
        wb = load_workbook(self.filename)
        final_data = []
        for sheet_name in case_config:
            test_data = []
            # 2.定位表单
            sheet = wb[sheet_name]  # 表单名是excel页面最下方的Sheet1,Sheet2
            for i in range(2, sheet.max_row + 1):
                sub_data = {}
                # 3.定位单元格,行列值,类似xy轴的坐标,取值
                sub_data['sheet_name'] = sheet_name  # 通过sheet.cell(*,*).value将一个个键值对放到sub_data字典内
                sub_data['case_id'] = sheet.cell(i, 1).value
                sub_data['title'] = sheet.cell(i, 2).value
                sub_data['method'] = sheet.cell(i, 3).value
                sub_data['url'] = sheet.cell(i, 4).value
                sub_data['headers'] = sheet.cell(i, 5).value
                sub_data['data'] = sheet.cell(i, 6).value
                sub_data['keys'] = sheet.cell(i, 7).value
                sub_data['expected'] = sheet.cell(i, 8).value
                test_data.append(sub_data)  # 将sub_data每一次执行后的字典放到test_data列表内

            if case_config[sheet_name] == 'all':
                for item in test_data:
                    final_data.append(item)  # 默认全部执行
            else:
                for item in test_data:  # 将符合条件的case存储到final_data内
                    if item['case_id'] in case_config[sheet_name]:
                        final_data.append(item)
        return final_data  # 最终执行case列表返回

    def write_back(self, sheet_name,row, cole,result):
        '''将报错信息写回文档的实例函数'''
        wb = load_workbook(self.filename)
        sheet = wb[sheet_name]
        sheet.cell(row, cole).value = result  # 将报错信息存储到对应表格内
        wb.save(self.filename)  # 写入后保存,否则没有保存成功

if __name__ == '__main__':
    res = DoExcel('/Users/lucky/pythonProject/yue/config/apii.xlsx').get_data()
    print(res)


 

你可能感兴趣的:(Python自动化,Python自动化)