python-Excel文件处理

2022/3/30 1:56:27

本文主要是介绍python-Excel文件处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

from openpyxl import load_workbook

class ReadExcel:
    def __init__(self, wb_name, sheet_name):
        self.wb = load_workbook(wb_name)
        self.sheet = self.wb[sheet_name]

    def read_all_datas(self):
        res_excel = []
        for row_id in range(1,self.sheet.max_row+1):
            res_excel_row = []
            for col_id in range(1,self.sheet.max_column+1):
                res_excel_row.append(self.sheet.cell(row_id, col_id).value)
            res_excel.append(res_excel_row)
        return res_excel

    def read_test_data(self):
        res_test_datas = []
        for i in range(1, self.sheet.max_row+1):
            res_test_data = {}
            res_test_data['method'] = self.sheet.cell(i,1).value
            res_test_data['url'] = self.sheet.cell(i,2).value
            res_test_data['data'] = eval(self.sheet.cell(i,3).value)
            res_test_data['expected'] = self.sheet.cell(i,4).value
            res_test_datas.append(res_test_data)
        return res_test_datas

    def get_header(self):
        header = []
        for i in range(1,self.sheet.max_column+1):
            header.append(self.sheet.cell(1,i).value)
        return header

    def get_title_data(self):
        header = self.get_header()
        test_datas = []
        for i in range(2, self.sheet.max_row+1):
            test_data = {}
            for j in range(1,self.sheet.max_column+1):
                test_data[header[j-1]] = self.sheet.cell(i,j).value
            test_datas.append(test_data)
        return header, test_datas


if __name__ == '__main__':
    res = ReadExcel("test_excel01.xlsx", 'test').read_all_datas()
    res1 = ReadExcel("test_excel01.xlsx", 'test').read_test_data()
    header, res2 = ReadExcel("test_excel02.xlsx", 'test').get_title_data()
    print(header)
    print(res2)

Excel文件格式一:

 

Excel文件格式二:

 



这篇关于python-Excel文件处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程