沈三废

导航

EXCEL的写入的脚本封装

写入excel,在封装时发现每次初始化都会把原来的excel数据清空,无法做到增量追加,网上找了不少答案都没有找到最优解;

最后是想先把原有的数据读取出来,再重新写入,最后写入新数据。考虑到后期测试用到的数据形式,做了对字典跟列表两种格式的处理,可以灵活实现数据的写入

具体实现思路:

数据写入封装两个方法:
1、历史数据的重写
a)源数据的读取
b)数据重写,以字典形式传入
2、新数据的写入
a)表头信息写入
b)具体数据的写入,以列表嵌套格式传入

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/25 19:19
# @Author : 沈三废
# @FileName: write_excel.py

from openpyxl import workbook from openpyxl import load_workbook from tools.read_excel import read_excel class write_excel: def __init__(self, filename, title): self.wb = workbook.Workbook() self.filename = filename self.title = title def __write_head(self, head_name, sheet): for i in range(0, len(head_name)): index = chr(65 + int(i)) # todo 超过26为待兼容 sheet[index + "1"].value = head_name[i] def __write_case_list(self, case, sheet): # case=[[],[],[]] for i in range(2, len(case) + 2): # 行 for j in range(1, len(case[0]) + 1): # 列 sheet.cell(row=i, column=j, value=str(case[i - 2][j - 1])) def __read_source_data(self, filename): # 源数据读取 case_list_all, sheet_list = [], [] wb = load_workbook(filename=filename) for sheet in wb: case_list = read_excel(filename=filename, sheetname=sheet.title).read_data() case_list_all.append(case_list) sheet_list.append(sheet.title) return case_list_all, sheet_list def __write_case_dict(self, case_list_all, sheet_list): for num, case in enumerate(case_list_all): if case == []: continue sh = self.wb.create_sheet(sheet_list[num], num) for i, key in enumerate(case[0]): index = chr(65 + int(i)) # todo 超过26为待兼容 sh[index + "1"].value = key for j in range(2, len(case) + 2): # 行 for k, key in enumerate(case[0]): sh.cell(row=j, column=k + 1, value=str(case[j - 2][key])) self.wb.save(self.filename) self.wb.close() def write_history_data(self): try: self.case_list_all, self.sheet_list = self.__read_source_data(filename=self.filename) self.__write_case_dict(case_list_all=self.case_list_all,sheet_list=self.sheet_list) del self.wb["Sheet"] print("历史数据重写成功!!") self.wb.save(self.filename) self.wb.close() except Exception as e: print("历史数据重写失败!!{}".format(e)) def write_new_data(self,head_name,case): sh=self.wb.create_sheet(self.title) self.__write_head(head_name=head_name,sheet=sh) self.__write_case_list(case=case,sheet=sh) self.wb.save(self.filename) self.wb.close() print("用例导入成功") if __name__ == '__main__': c1=write_excel(filename="./test01.xlsx", title="测试") c1.write_history_data() c1.write_new_data(head_name=["who","do"],case=[["孙悟空","吃早饭"],["比克","练功"]])

  

 

 

如果有更好的实现方法,欢迎骚扰博主,让小弟学习学习~~~

posted on 2021-08-25 20:32  沈三废  阅读(85)  评论(0编辑  收藏  举报