利用openpyxl模块实现一个具有上下文管理器功能的读写excel封装

from openpyxl import load_workbook


class DoExcel:
    def __init__(self, file_path, sheet_name):
        """
        :param file_path: 文件路径
        :param sheet_name: sheet表单名
        """
        self.wb = load_workbook(file_path)
        self.sheet_name = sheet_name

    def __enter__(self):
        sh = self.wb[self.sheet_name]
        row = sh.max_row + 1
        col = sh.max_column + 1
        test_data = ({sh.cell(1, j).value: sh.cell(r, j).value for j in range(1, col)} for r in
                     range(2, row))  # 生成器表达式
        return list(test_data)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.wb.close()


if __name__ == '__main__':
    data_case_path = 'a_data_case.xlsx'
    with DoExcel(data_case_path, "登录") as ex:
        for i in ex:
            print(i)

你可能感兴趣的:(excel,python,开发语言)