51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 4074|回复: 1
打印 上一主题 下一主题

[原创] EXCEL转换为XML如何用Python实现?

[复制链接]
  • TA的每日心情
    擦汗
    昨天 08:46
  • 签到天数: 981 天

    连续签到: 1 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2021-7-1 14:17:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    本文将结合作者项目实践,介绍如何将EXCEL文件通过python转换为XML,以方便导入到Testlink中(Testlink仅支持XML文件的导入),并且顺便介绍一下Python常见的错误及解决方案。希望对大家有所帮助。
    声明:文中转换工具涉及的代码是借鉴了其他帖子上的一部代码,结合本文作者项目的实际情况,编写而成,原始出处已经不得而知,如有雷同,不是巧合。
    1 输出EXCEL格式的测试用例文件
    1.1 测试用例使用如下模板输出,保存为XXX.xlsx文件,例如命名case.xlsx

    1.2 部分字段解释:
    1.2.1 功能点
    一般EXCEL文件的一个Sheet页代表一个模块,在一个模块内部分为多个功能点,通过一个或多个测试用例对每个功能点进行一一覆盖。功能点字段就是对模块进行结构化划分的。
    1.2.2 测试方式
    该字段用以标识测试方式,是手工测试还是自动化测试,方便日后识别哪些用例是自动化实现的用例
    1.2.3 关键字
    这个字段可以多种用途,例如用于识别产品形态,识别用例输出版本,或者用于识别质量属性,都是可以的。作者项目中,是用于识别质量属性的,例如功能测试、性能测试、易用性测试等等
    1.2.4 重要性
    填写P0/P1/P2,表示三个用例级别:高中低
    1.2.5 设计人员
    该字段是用来标识用例的作者的,用于方便可追溯性或用例维护。
    2 安装Python 3
    由于本文中的EXCEL转换为xml的工具是用python语言写的,所以,首先,需要安装python运行环境,本文中用的是3.6.2。
    若已经安装了Python 3,则跳过此步骤。
    2.1 下载安装python
    Python3可以去网上免费下载安装,地址为:
    https://www.python.org/ftp/python/3.6.2/python-3.6.2-amd64.exe
    2.2 配置运行环境
    安装完python后,配置环境变量
    我的电脑-》属性-》高级系统设置-》高级-》环境变量,在用户变量部分,找到变量名为path的,点击编辑,新建,将Python安装目录及pip所在目录都添加到环境变量表中,此例中为:\Python3d6\Python36\和F:\Python3d6\Python36\Scripts\

    具体的步骤在本文中就不赘述了,需要的可以自己去网上找。
    2.3 调试python及pip
    配置好环境变量后,就在CMD下,运行python和pip,安装py脚本中涉及的python库。
    但是作者在调试过程中,曾经遇到了如下的几个问题,供大家参考:
    2.3.1 错误一
    现象:
    Cmd命令行下,敲pip报错,敲python正常
    具体信息如下:

    C:\Users\Administrator>pip
    Fatal error in launcher: Unable to create process using '"c:\python36\python3.exe""F:\Python3d6\Python36\Scripts\pip.exe" ': ???????????
    C:\Users\Administrator>python3
    Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    前置条件:
    1)Python安装目录为F:\Python3d6\Python36\
    2)已经将F:\Python3d6\Python36\和F:\Python3d6\Python36\Scripts\配置到环境变量中

    排查思路:
    1、第一步
    经初步判断,感觉是路径有问题
    随后,将安装路径改为F:\Python36\,即将“Python3d6”这层文件夹去掉,并重新配置环境变量
    现象:Cmd命令行下,敲python正常,敲pip仍然后报错
    报错如下:

    1. C:\Users\Administrator>pip install pywin32
    2. Fatal error in launcher: Unable to create process using '"c:\python36\python3.exe""F:\Python36\Scripts\pip.exe" install pywin32': ???????????
    复制代码
    2、第二步
    排除环境变量配置问题:
    cd到安装目录下,执行pip,仍然报错
    具体报错信息如下:


    1. F:\Python36\Scripts>pip install pywin32
    2. Fatal error in launcher: Unable to create process using '"c:\python36\python3.exe""F:\Python36\Scripts\pip.exe" install pywin32': ???????????
    复制代码
    3、第三步
    尝试把python整个文件夹从F盘移动到C盘,然后修改好环境变量
    执行pip,没有报错,问题搞定
    打印信息如下:


    C:\Users\Administrator>pip
    Usage:
      pip <command> [options]
    Commands:
      install                     Install packages.
      download                    Download packages.
      uninstall                   Uninstall packages.
    ......
    2.3.2 错误二
    现象:
    Python运行.py文件报错 :NameError name 'reload' is not defined
    相关代码:

    import sys
    reload(sys)
    sys.setdefaultencoding("utf-8")
    原因:
    setdefaultencoding是python 2的sys库里边的函数,Python 3 的 sys 库里面已经没有 setdefaultencoding() 函数,并且Python 3 系统默认使用的就是utf-8编码
    解决方案:
    将sys.setdefaultencoding("utf-8")代码整行去掉即可
    2.3.3 错误三
    现象:调用print函数出错
    具体报错信息如下:



    1. C:\Users\Administrator>python3 F:\case\operate.py
    2.   File "F:\case\operate.py", line 46
    3.     print 'str=', str
    4.                ^
    5. SyntaxError: Missing parentheses in call to 'print'
    复制代码


    原因:


    python2.X版本与python3.X版本输出方式不同造成的


    解决方案:


    Print函数后面加上括号()




    1.1.1 Python2代码与Python3代码不兼容

    其实将python代码用python3执行,很多问题都是由于python2版本和python版本代码不兼容导致的。


    下面以实际的例子,介绍一种python2代码转换成python3代码的方法:


    假设:python 2.Xpython 3.X转换文件2to3.py的路径为C:\Python36\Tools\scripts


    待转换的文件operate.py的路径为D:\python2to3


    CMD下执行如下命令,即可将该python2文件转换为python3文件


    python3 C:\Python36\Tools\scripts\2to3.py -wD:\python2to3\operate.py


    出现如下打印说明转换过程成功
    1. C:\Users\Administrator>python3 C:\Python36\Tools\scripts\2to3.py -w D:\python2to3\operate.py
    2. RefactoringTool: Skipping optional fixer: buffer
    3. RefactoringTool: Skipping optional fixer: idioms
    4. RefactoringTool: Skipping optional fixer: set_literal
    5. RefactoringTool: Skipping optional fixer: ws_comma
    6. RefactoringTool: Refactored D:\python2to3\operate.py
    7. --- D:\python2to3\operate.py    (original)
    8. +++ D:\python2to3\operate.py    (refactored)
    9. [url=home.php?mod=space&uid=40658]@@[/url] -1,7 +1,8 @@
    10. # coding:utf-8
    11. import os,re,xlrd
    12. import sys
    13. -reload(sys)
    14. +import imp
    15. +imp.reload(sys)
    16. sys.setdefaultencoding("utf-8")

    17. from easy_excel import easy_excel
    18. @@ -43,7 +44,7 @@
    19.                  def actions_add_div(str):
    20.                      if str:
    21.                          new_action_str=""
    22. -                        print 'str=', str
    23. +                        print('str=', str)
    24.                          for str_index in str.split('\n'):
    25.                              newline=str_index + "" + "</div>" + "<div>" + "" + "</p>" + "<p>"
    26.                              new_action_str+=newline
    27. @@ -122,16 +123,16 @@

    28. if __name__ == "__main__":

    29. -    print os.path.abspath('.')
    30. +    print(os.path.abspath('.'))
    31.      excellist=[]
    32.      #列出当前目录下的所有.xml文件
    33.      for fullname in iterbrowse(os.path.abspath('.')):
    34. -        print fullname
    35. +        print(fullname)
    36.          obj1=re.compile(r'([\W\w]*)(\.xlsx)
    37. [/color][/align]



    38. [/backcolor]

    39. [backcolor=rgb(247, 247, 247)]
    40. [/backcolor]



    41. )
    42.          for m in obj1.finditer(fullname):
    43. -            print m.group()
    44. +            print(m.group())
    45.              excellist.append(m.group())
    46. -    print excellist
    47. +    print(excellist)
    48.      for fileName in excellist:
    49.          fileName=fileName.split('\\')[-1]
    50.          file_data = xlrd.open_workbook(fileName)
    51. @@ -139,12 +140,12 @@
    52.          sheetList=[]
    53.          for index in range(sheetnum):
    54.              sheet_name=file_data.sheets()[index].name
    55. -            print sheet_name
    56. +            print(sheet_name)
    57.              sheetList.append(sheet_name)
    58. -        print sheetList
    59. +        print(sheetList)
    60.          for sheetName in sheetList:
    61.              test = operate(fileName, sheetName)
    62.              test.xlsx_to_dic(sheetName)
    63.              test.dic_to_xml(fileName, sheetName)
    64. -    print "Convert success!"
    65. +    print("Convert success!")
    66.      os.system('pause')
    67. RefactoringTool: Files that were modified:
    68. RefactoringTool: D:\python2to3\operate.py
    复制代码












    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

  • TA的每日心情
    擦汗
    昨天 08:46
  • 签到天数: 981 天

    连续签到: 1 天

    [LV.10]测试总司令

    2#
     楼主| 发表于 2021-7-1 14:23:41 | 只看该作者
    从日志中可以看出,转换过程中,对哪些行进行了修改一目了然
    如果某python文件不需要转换,则会出现如下的打印:
    1. C:\Users\Administrator>python3 C:\Python36\Tools\scripts\2to3.py -w D:\python2to3\operate.py
    2. RefactoringTool: Skipping optional fixer: buffer
    3. RefactoringTool: Skipping optional fixer: idioms
    4. RefactoringTool: Skipping optional fixer: set_literal
    5. RefactoringTool: Skipping optional fixer: ws_comma
    6. RefactoringTool: No changes to D:\python2to3\operate.py
    7. RefactoringTool: Files that need to be modified:
    8. RefactoringTool: D:\python2to3\operate.py
    复制代码
    3 将EXCEL转换为xml
    安装好python库后,将用例表格与脚本放入同目录(脚本代码在文末),如下:


    注意:用例表格的名称需用英文,不要含有中文
    cd到表格和脚本所在目录,然后运行 operate.py 文件,打印如下:
    1. D:\python2to3>python3 operate.py
    2. D:\python2to3
    3. D:\python2to3\case.xlsx
    4. D:\python2to3\case.xlsx
    5. D:\python2to3\easy_excel.py
    6. D:\python2to3\easy_excel.py.bak
    7. D:\python2to3\operate.py
    8. D:\python2to3\operate.py.bak
    9. D:\python2to3\__pycache__\easy_excel.cpython-36.pyc
    10. ['D:\\python2to3\\case.xlsx']
    11. XX功能模块1
    12. XX功能模块2
    13. ['XX功能模块1', 'XX功能模块2']
    14. ('str=', '1.步骤一\n2.步骤二\n3.步骤三')
    15. ('str=', '1.步骤一\n2.步骤二\n3.步骤三')
    16. Convert success!
    17. 请按任意键继续. . .
    复制代码
    转换成功,按照EXCEL的sheet页输出两个XML文件:case.xlsx_XX功能模块1.xml和case.xlsx_XX功能模块2.xml,可以用来导入到Testlink用例管理系统中

    4 代码
    4.1 easy_excel.py
    1. # coding=utf-8
    2. from xml.etree import ElementTree
    3. from win32com.client import Dispatch
    4. import win32com.client
    5. import os
    6. import sys
    7. import imp
    8. imp.reload(sys)

    9. class easy_excel:
    10.     def __init__(self, filename=None):
    11.         self.xlApp = win32com.client.Dispatch('Excel.Application')

    12.         if filename:
    13.             self.filename = os.getcwd() + "\\" + filename
    14.             # self.xlApp.Visible=True
    15.             self.xlBook = self.xlApp.Workbooks.Open(self.filename)
    16.         else:
    17.             # self.xlApp.Visible=True
    18.             self.xlBook = self.xlApp.Workbooks.Add()
    19.             self.filename = ''

    20.     def save(self, newfilename=None):
    21.         if newfilename:
    22.             self.filename = os.getcwd() + "\\" + newfilename
    23.             # if os.path.exists(self.filename):
    24.             # os.remove(self.filename)
    25.             self.xlBook.SaveAs(self.filename)
    26.         else:
    27.             self.xlBook.Save()

    28.     def close(self):
    29.         self.xlBook.Close(SaveChanges=0)
    30.         self.xlApp.Quit()

    31.     def getCell(self, sheet, row, col):
    32.         sht = self.xlBook.Worksheets(sheet)
    33.         return sht.Cells(row, col).Value

    34.     def setCell(self, sheet, row, col, value):
    35.         sht = self.xlBook.Worksheets(sheet)
    36.         sht.Cells(row, col).Value = value
    37.         # 设置居中
    38.         sht.Cells(row, col).HorizontalAlignment = 3
    39.         sht.Rows(row).WrapText = True

    40.     def mergeCells(self, sheet, row1, col1, row2, col2):
    41.         start_coloum = int(dic_config["start_coloum"])
    42.         # 如果这列不存在就不合并单元格
    43.         if col2 != start_coloum - 1:
    44.             sht = self.xlBook.Worksheets(sheet)
    45.             sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Merge()
    46.             # else:
    47.             # print 'Merge cells coloum %s failed!' %col2

    48.     def setBorder(self, sheet, row, col):
    49.         sht = self.xlBook.Worksheets(sheet)
    50.         sht.Cells(row, col).Borders.LineStyle = 1

    51.     def set_col_width(self, sheet, start, end, length):
    52.         start += 96
    53.         end += 96
    54.         msg = chr(start) + ":" + chr(end)
    55.         # print msg
    56.         sht = self.xlBook.Worksheets(sheet)
    57.         sht.Columns(msg.upper()).ColumnWidth = length
    复制代码
    4.2 operate.py





    1. # coding:utf-8
    2. import os,re,xlrd
    3. import sys
    4. import imp
    5. imp.reload(sys)

    6. from easy_excel import easy_excel
    7. class operate():
    8.     def __init__(self, ExcelFileName, SheetName):
    9.         self.excelFile = ExcelFileName
    10.         self.excelSheet = SheetName
    11.         self.temp = easy_excel(self.excelFile)
    12.         self.dic_testlink = {}
    13.         self.row_flag = 2
    14.         self.testsuite = self.temp.getCell(self.excelSheet, 2, 2)
    15.         #print 'self.testsuite=',self.testsuite
    16.         self.dic_testlink[self.testsuite] = {"node_order": "13", "details": "", "testcase": []}
    17.         self.content = ""
    18.         self.content_list = []

    19.     def xlsx_to_dic(self, SheetName):
    20.         while True:
    21.             testcase = {"name": "", "node_order": "100", "externalid": "", "version": "1", "summary": "",
    22. "preconditions": "", "execution_type": "1", "importance": "3", "steps": [], "keywords": "P1", "author":""}
    23.             testcase["name"] = self.temp.getCell(self.excelSheet, self.row_flag, 5)
    24.             testcase["summary"] = self.temp.getCell(self.excelSheet, self.row_flag, 3)
    25.             testcase["preconditions"] = self.temp.getCell(self.excelSheet, self.row_flag, 6)
    26.             execution_type = self.temp.getCell(self.excelSheet, self.row_flag, 9)
    27.             testcase["keywords"] = self.temp.getCell(self.excelSheet, self.row_flag, 10)
    28.             testcase["author"] = self.temp.getCell(self.excelSheet, self.row_flag, 11)
    29.             if execution_type == "自动":
    30.                 testcase["execution_type"] = 2
    31.             step_number = 1
    32.             importance = self.temp.getCell(self.excelSheet, self.row_flag, 4)
    33.             if importance == "基本功能" or importance == "P1":
    34.                 testcase["importance"]="2"
    35.             elif importance == "拓展" or importance == "P2":
    36.                 testcase["importance"] = "1"
    37.             while True:
    38.                 step = {"step_number": "", "actions": "", "expectedresults": "", "execution_type": ""}
    39.                 step["step_number"] = step_number
    40.                 step["actions"] = self.temp.getCell(self.excelSheet, self.row_flag, 7)
    41.                 def actions_add_div(str):
    42.                     if str:
    43.                         new_action_str=""
    44.                         print(('str=', str))
    45.                         for str_index in str.split('\n'):
    46.                             newline=str_index + "" + "</div>" + "<div>" + "" + "</p>" + "<p>"
    47.                             new_action_str+=newline
    48.                         return new_action_str[:-21]
    49.                 step["actions"]=actions_add_div(step["actions"])
    50.                 step["expectedresults"] = self.temp.getCell(self.excelSheet, self.row_flag, 8)
    51.                 testcase["steps"].append(step)
    52.                 step_number += 1
    53.                 self.row_flag += 1
    54.                 if self.temp.getCell(self.excelSheet, self.row_flag, 1) is not None or self.temp.getCell(self.excelSheet, self.row_flag, 5) is None:
    55.                     break
    56.             # print testcase

    57.             self.dic_testlink[self.testsuite]["testcase"].append(testcase)
    58.             # print self.row_flag
    59.             if self.temp.getCell(self.excelSheet, self.row_flag, 5) is None and self.temp.getCell(self.excelSheet, self.row_flag + 1, 5) is None:
    60.                 break
    61.         self.temp.close()
    62.         # print self.dic_testlink

    63.     def content_to_xml(self, key, value=None):
    64.         if key == 'step_number' or key == 'execution_type' or key == 'node_order' or key == 'externalid' or key == 'version' or key == 'importance':
    65.             return "<" + str(key) + "><![CDATA[" + str(value) + "]]></" + str(key) + ">"
    66.         elif key == 'actions' or key == 'expectedresults' or key == 'summary' or key == 'preconditions':
    67.             return "<" + str(key) + "><![CDATA[<div>" + str(value) + "</div> ]]></" + str(key) + ">"
    68.         elif key == 'keywords':
    69.             return '<keywords><keyword name="' + str(value) + '"><notes><![CDATA[ aaaa ]]></notes></keyword></keywords>'
    70.         elif key == 'name':
    71.             return '<testcase name="' + str(value) + '">'
    72.         elif key == 'author':
    73.             return '<custom_fields><custom_field><name><![CDATA[设计人员]]></name><value><![CDATA[%s]]></value></custom_field></custom_fields>' % str(value)
    74.         else:
    75.             return '##########'

    76.     def dic_to_xml(self, ExcelFileName, SheetName):
    77.         testcase_list = self.dic_testlink[self.testsuite]["testcase"]
    78.         for testcase in testcase_list:
    79.             for step in testcase["steps"]:
    80.                 self.content += "<step>"
    81.                 self.content += self.content_to_xml("step_number", step["step_number"])
    82.                 self.content += self.content_to_xml("actions", step["actions"])
    83.                 self.content += self.content_to_xml("expectedresults", step["expectedresults"])
    84.                 self.content += self.content_to_xml("execution_type", step["execution_type"])
    85.                 self.content += "</step>"
    86.             self.content = "<steps>" + self.content + "</steps>"
    87.             self.content = self.content_to_xml("importance", testcase["importance"]) + self.content
    88.             self.content = self.content_to_xml("execution_type", testcase["execution_type"]) + self.content
    89.             self.content = self.content_to_xml("preconditions", testcase["preconditions"]) + self.content
    90.             self.content = self.content_to_xml("summary", testcase["summary"]) + self.content
    91.             self.content = self.content_to_xml("version", testcase["version"]) + self.content
    92.             self.content = self.content_to_xml("externalid", testcase["externalid"]) + self.content
    93.             self.content = self.content_to_xml("node_order", testcase["node_order"]) + self.content
    94.             self.content = self.content + self.content_to_xml("keywords", testcase["keywords"])
    95.             self.content = self.content_to_xml("name", testcase["name"]) + self.content
    96.             self.content = self.content + self.content_to_xml("author", testcase["author"])
    97.             self.content = self.content + "</testcase>"
    98.             self.content_list.append(self.content)
    99.             self.content = ""
    100.         self.content = "".join(self.content_list)
    101.         self.content = '<testsuite name="' + self.testsuite + '">' + self.content + "</testsuite>"
    102.         self.content = '<?xml version="1.0" encoding="UTF-8"?>' + self.content
    103.         self.write_to_file(ExcelFileName, SheetName)

    104.     def write_to_file(self, ExcelFileName, SheetName):
    105.         xmlFileName = ExcelFileName + '_' + SheetName + '.xml'
    106.         cp = open(xmlFileName, "w")
    107.         cp.write(self.content)
    108.         cp.close()

    109. #遍历某个文件目录下的所有文件名称
    110. def iterbrowse(path):
    111.     for home, dirs, files in os.walk(path):
    112.         for filename in files:
    113.             yield os.path.join(home, filename)


    114. if __name__ == "__main__":

    115.     print((os.path.abspath('.')))
    116.     excellist=[]
    117.     #列出当前目录下的所有.xml文件
    118.     for fullname in iterbrowse(os.path.abspath('.')):
    119.         print(fullname)
    120.         obj1=re.compile(r'([\W\w]*)(\.xlsx)
    121. )
    122.         for m in obj1.finditer(fullname):
    123.             print((m.group()))
    124.             excellist.append(m.group())
    125.     print(excellist)
    126.     for fileName in excellist:
    127.         fileName=fileName.split('\\')[-1]
    128.         file_data = xlrd.open_workbook(fileName)
    129.         sheetnum=len(file_data.sheets())
    130.         sheetList=[]
    131.         for index in range(sheetnum):
    132.             sheet_name=file_data.sheets()[index].name
    133.             print(sheet_name)
    134.             sheetList.append(sheet_name)
    135.         print(sheetList)
    136.         for sheetName in sheetList:
    137.             test = operate(fileName, sheetName)
    138.             test.xlsx_to_dic(sheetName)
    139.             test.dic_to_xml(fileName, sheetName)
    140.     print("Convert success!")
    141.     os.system('pause')
    复制代码

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    回复 支持 反对

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /2 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-7-9 07:33 , Processed in 0.070481 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表