pythonパッケージ関数excelデータの自動読み書き

8305 ワード

pythonパッケージ関数excelデータの自動読み書き
EXcelドキュメントを操作するには、openpyxlライブラリ、pip install openpyxlをインストールする必要があります.
import openpyxl


class CaseData:
    pass


class HandleExcel:

    def __init__(self, filename, sheetname):
        """         """
        self.filename = filename
        self.sheetname = sheetname

    def open(self):
        #     
        self.wb = openpyxl.load_workbook(self.filename)
        #     
        self.sh = self.wb[self.sheetname]

    def read_excel(self):
        """excel    """
        self.open()
        #           
        rows = list(self.sh.rows)
        #      ,             
        title = [x1.value for x1 in rows[0]]
        #            
        cases = []
        #            
        for row in rows[1:]:
            #            
            list1 = [x2.value for x2 in row]
            #   CaseData    
            case = CaseData()
            #             ,  
            for i in zip(title, list1):
                #   setattr    ,         ,        
                setattr(case, i[0], i[1])
            #              
            cases.append(case)
        #      
        self.wb.close()

        return cases

    def write_excel(self, row, column, value):
        """excel    """
        #         
        self.open()
        #     
        self.sh.cell(row=row, column=column, value=value)
        #     
        self.wb.save(self.filename)
        #      
        self.wb.close()


if __name__ == '__main__':
    read = HandleExcel('datas.xlsx', 'test')
    # print(read.read_excel())
    read.write_excel(1, 1, 'Pass')