python3实现xmind用例转excel

  1 import xmindparser
  2 import xlwt, xlrd
  3 from xlutils.copy import copy
  4 from xlwt import Worksheet
  5 from xmindparser import xmind_to_dict
  6 import datetime
  7 import os
  8 import re
  9 import traceback
 10 
 11 # 当前时间戳
 12 a = datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')
 13 timestp = re.sub(r'-|:|\s', '', str(a))
 14 
 15 # 根目录
 16 base_dir = os.path.abspath(os.path.dirname(__file__))
 17 
 18 # xmindparser配置
 19 xmindparser.config = {
 20     'showTopicId': False,  # 是否展示主题ID
 21     'hideEmptyValue': True  # 是否隐藏空值
 22 }
 23 
 24 
 25 def traversal_xmind(root, rootstring, lisitcontainer, flag):
 26     """
 27     功能:递归dictionary文件得到容易写入Excel形式的格式。
 28     注意:rootstring都用str来处理中文字符
 29     @param root: 将xmind处理后的dictionary文件
 30     @param rootstring: xmind根标题
 31     @param lisitcontainer: list容器存放数据
 32     @param flag: 特殊标记标签
 33     """
 34     try:
 35         # 判断数据是否是字典类型
 36         if isinstance(root, dict):
 37             print('root1:', root)
 38             # 如果这个字典的key中同时有title和topics,则可认为这个title有下级分支
 39             if 'title' in root.keys() and 'topics' in root.keys():
 40                 traversal_xmind(root['topics'], str(rootstring), lisitcontainer, True)
 41             # 如果这个字典的key中有title且没有topics,则可认为这个title是最末端
 42             if 'title' in root.keys() and 'topics' not in root.keys():
 43                 traversal_xmind(root['title'], str(rootstring), lisitcontainer, True)
 44 
 45         # 判断数据是否是列表类型
 46         elif isinstance(root, list):
 47             #
 48             flag = True
 49             # 遍历列表
 50             for sonroot in root:
 51                 # sonroot只可能是dict类型
 52                 # 如果这个字典的key中同时有title和topics,则可认为这个title有下级分支
 53                 if flag:
 54                     if 'title' in sonroot.keys() and 'topics' in sonroot.keys():
 55                         traversal_xmind(sonroot['topics'], str(rootstring) + "!" + sonroot['title'], lisitcontainer,
 56                                         True)
 57                     # 如果这个字典的key中有title且没有topics,则可认为这个title是最末端
 58                     elif 'title' in sonroot.keys() and 'topics' not in sonroot.keys():
 59                         # # 判断蓝色感叹号标识(前置条件)是否存在
 60                         if 'makers' in sonroot.keys() and 'symbol-info' in sonroot['makers']:
 61                             case = str(rootstring) + "!" + root[0]['title'] + "!" + root[1]['title'] + "!" + \
 62                                    root[1]['topics'][0]['title']
 63                             # 如果有特殊标签,则改变flag状态
 64                             flag = False
 65                             traversal_xmind(case, case, lisitcontainer, flag)
 66                         else:
 67                             case = str(rootstring) + "!" + sonroot['title']
 68                             traversal_xmind(case, case, lisitcontainer, True)
 69 
 70         # 判断数据是否是字符串类型
 71         elif isinstance(root, str):
 72             # lisitcontainer.append(str(rootstring.replace('\n', '')))  # 此处是去掉一步骤多结果情况直接拼接
 73             lisitcontainer.append(str(rootstring))  # 此处是一步骤多结果时,多结果合并
 74             # print('lisitcontainer:', lisitcontainer)
 75     except:
 76         tips = 'xmind处理异常,请联系Dora!!!'
 77         # 输出异常信息
 78         traceback.print_exc()
 79 
 80 # 将xmind中的每条用例提取出来,放入列表中,以逗号分隔
 81 def get_case(root):
 82     rootstring = root['title']
 83     lisitcontainer = []
 84     traversal_xmind(root, rootstring, lisitcontainer, True)
 85     return lisitcontainer
 86 
 87 # 写入第b行的用例数据内容
 88 def write_sheet(Worksheet, b, casename, casestep, expectresult):
 89     '''
 90     功能解释:去掉用例中的换行符,写入一条用例到Excel中
 91     @param Worksheet: excel表对象
 92     @param b: 写入的数据在表中所处的行数
 93     @param casename: 用例名称
 94     @param casestep: 用例操作
 95     @param expectresult: 期望结果
 96     '''
 97     # 用例名称
 98     caseName = re.sub(r'\r\n', '', str(casename))
 99     # 用例步骤
100     caseStep = re.sub(r'\r\n', '', str(casestep))
101     # 期望结果
102     expectResult = re.sub(r'\r\n', '', str(expectresult))
103     Worksheet.write(b, 0, caseName)  # 用例名称
104     Worksheet.write(b, 1, caseStep)  # 用例步骤
105     Worksheet.write(b, 2, expectResult)  # 预期结果
106 
107 # 处理xmind数据
108 def deal_with_list(Worksheet, case_list):
109     '''
110     功能解释:处理从xmind转换过来的用例list,并写入Excel中
111     @param Worksheet: excel表对象
112     @param case_list: 通过xmind转换好的用例列表
113     '''
114     tips = 'excel表格处理成功!!!'
115 
116     b = 1  # 记录写了多少行
117     for row_case in case_list:
118         case = row_case.split("!")  # 用‘!’分隔,存在list中,这是一条用例
119         caselength = len(case)
120         try:
121             if '前置条件' in row_case:
122                 casename = ''
123                 for i in range(0, caselength - 3):
124                     casename += case[i]  # 用例标题,(默认为从倒数第4个下标往前都是用例标题)
125                 casestep = case[-3] + case[-2]  # 用例步骤,(倒数第2个下标是步骤,倒数第3个下标识前置条件(必须有前置条件)
126                 expectresult = case[-1]  # 预期结果,(倒数第1个下标是预期结果)
127                 write_sheet(Worksheet, b, casename, casestep, expectresult)  # 写入Excel
128 
129             else:
130                 casename = ''
131                 for i in range(0, caselength - 2):
132                     casename += case[i]  # 用例标题,(无前置条件的情况下,默认为从倒数第3个下标往前都是用例标题)
133                 casestep = case[-2]  # 用例步骤,(倒数第2个下标是步骤)
134                 expectresult = case[-1]  # 预期结果,(倒数第1个下标是预期结果)
135                 # print(expectresult)
136                 write_sheet(Worksheet, b, casename, casestep, expectresult)  # 写入Excel
137         except:
138             tips = 'excel表格处理异常,请联系Dora!!!'
139             print('异常tips:', tips)
140             # 输出异常信息
141             traceback.print_exc()
142         b = b + 1
143     return tips
144 
145 def xmindToexcelfile(uploadPath):
146     # 创建一个Workbook对象 编码encoding
147     Workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
148     # 添加一个sheet工作表、sheet名命名为Sheet1、cell_overwrite_ok=True允许覆盖写
149     Worksheet = Workbook.add_sheet('Sheet1', cell_overwrite_ok=True)
150     Worksheet.write(0, 0, '用例名称')
151     Worksheet.write(0, 1, '操作步骤')
152     Worksheet.write(0, 2, '预期结果')
153     root = xmind_to_dict(uploadPath)[0]['topic']  # 解析成dict数据类型xmindparser.xmind_to_dict(filePath)
154     print('root:', root)
155     case_list = get_case(root)
156     print('case:', case_list)
157     tips = deal_with_list(Worksheet, case_list)
158     # Excel表保存的文件名字
159     savepath = os.path.abspath(os.path.dirname(__file__)) + '\\excelFiles\\' + root["title"] + timestp + ".xls"
160     Workbook.save(savepath)  # 此处可以填写生成文件的路径
161     return tips
162 
163 xmindToexcelfile('中心主题.xmind')

目录结构:

 

XMIND用例截图:

 

 转化用例截图:

 

posted @ 2024-03-11 20:13  Doraaaaaaaaaa  阅读(111)  评论(0编辑  收藏  举报