excel测试用例写入word表格

封装工具类

import openpyxl as openpyxl
from docx import Document
from copy import deepcopy

from docx.shared import Cm

class ExcelUtils():
    def __init__(self, filePath, sheet_name):
        self.file_path = filePath
        self.sheet_name = sheet_name
        self.wb = openpyxl.load_workbook(self.file_path)

    def readOneLine(self, row=1):
        ws = self.wb[self.sheet_name]
        cols = ws.max_column
        row_list = []
        for i in range(1, cols + 1):
            cell_value = ws.cell(row, i).value
            row_list.append(cell_value)
            i += 1
        return row_list

    def readRows(self):
        ws = self.wb[self.sheet_name]
        rows = ws.max_row
        return rows

    def readCols(self):
        ws = self.wb[self.sheet_name]
        cols = ws.max_column
        return cols


class DocxUtils():

    def creatTable(self, rowz, colz, style):
        doc = Document()
        table = doc.add_table(rows=rowz, cols=colz, style=style)
        table.cell(0, 1).merge(table.cell(0, colz - 1))
        table.cell(1, 1).merge(table.cell(1, colz - 1))
        table.cell(2, 1).merge(table.cell(2, colz - 1))
        table.cell(3, 1).merge(table.cell(3, colz - 1))
        table.cell(4, 1).merge(table.cell(4, colz - 1))
        table.cell(5, 1).merge(table.cell(5, colz - 1))
        table.cell(6, 0).merge(table.cell(6, colz - 1))
        table.cell(rowz - 3, 1).merge(table.cell(rowz - 3, colz - 1))
        table.cell(rowz - 2, 0).merge(table.cell(rowz - 2, 1))
        table.cell(rowz - 1, 0).merge(table.cell(rowz - 1, 1))

        # 设置单元格的宽度和高度
        table.cell(0,0).width = Cm(4)
        table.cell(1,0).width = Cm(4)
        table.cell(2,0).width = Cm(4)
        table.cell(3,0).width = Cm(4)
        table.cell(4,0).width = Cm(4)
        table.cell(5,0).width = Cm(4)
        table.cell(7,0).width = Cm(2)
        table.cell(8,0).width = Cm(2)
        table.cell(9,0).width = Cm(2)


        doc.save("C:\\Users\\...\\Desktop\\测试报告.docx")

    def copyTable(self, file_path, count, save_path):
        doc = Document(file_path)
        table = doc.tables[0]

        i = 0
        while i < count:
            new_table = deepcopy(table)
            paragraph = doc.add_paragraph()
            paragraph._p.addnext(new_table._element)
            i += 1
        doc.save(save_path)

    def remove_row(table, row):
        tbl = table._tbl
        tr = row._tr
        tbl.remove(tr)

main.py

from docx import Document

from utils import ExcelUtils
from utils import DocxUtils

if __name__ == '__main__':

    # 必填项
    # excel文件位置、工作表名称
    excelpath = "C:\\Users\\...\\Desktop\\系统管理测试用例.xlsx"
    sheetname = "Sheet1"
    # 设置读取excel文件的起始行和结束行
    start_row = 5
    end_row = 35
    # 模板的位置、生成文件的位置
    templatefilepath= "C:\\Users\\...\\Desktop\\报告.docx"
    savefilepath = "C:\\Users\\...\\Desktop\\报告2.docx"
    # 设置写入word表格的起始行以及保留结尾的行数(默认是3)
    startwriterow = 8
    # 根据不同的模板文件还需要手动设置 写入的单元坐标

    # 创建工具类对象
    exc_util = ExcelUtils(excelpath, sheetname)
    doc_util = DocxUtils()
    # 创建模板文件,包含一个空表格
    # doc_util.creatTable(13, 5, "Table Grid")
    # 根据模板中的一个表格复制出多个表格
    doc_util.copyTable(templatefilepath, 1 + end_row - start_row, savefilepath)
    # 打开创建好的word模板,将用于填充内容
    document = Document(savefilepath)

    # 循环读取每一个行的excel数据并写入word表格
    for i in range(start_row, end_row):
        # 返回每一行的数据列表
        result = exc_util.readOneLine(i)
        print(result)
        # 根据换行符号分割“操作步骤”
        operate_steps = result[8].split("\n")
        print(operate_steps)
        # 根据换行符号分割“预期结果”
        except_data = result[9].split("\n")
        print(except_data)

        step_len = len(operate_steps) if len(operate_steps) > len(except_data) else len(except_data)
        table = document.tables[i - start_row]
        rows = len(table.rows)
        # 删除多余的行
        for i in range(step_len + startwriterow, rows - 3):
            row = table.rows[len(operate_steps) + startwriterow]
            DocxUtils.remove_row(table, row)
        # 写入文本
        for i in range(startwriterow, step_len + startwriterow):
            cell_list = table.rows[i].cells
            # print(len(cell_list))
            if len(operate_steps) - (i - startwriterow) <= 0:
                cell_list[3].text = ""
            else:
                cell_list[3].text = operate_steps[i - startwriterow]
            if len(except_data) - (i - startwriterow) <= 0:
                cell_list[5].text = ""
            else:
                cell_list[5].text = except_data[i - startwriterow]
            cell_list[7].text = "与预期结果一致"
    document.save(savefilepath)

docx模板样例

excel样例

结果展示

posted @   梁伯熹  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示