技术干货丨Python轻松实现EXCEL转XML,项目实战
yuyutoo 2024-10-12 01:55 10 浏览 0 评论
本文将结合作者项目实践,介绍如何将EXCEL文件通过python转换为XML,以方便导入到Testlink中(Testlink仅支持XML文件的导入),并且顺便介绍一下Python常见的错误及解决方案,希望对大家有所帮助。
声明:文中转换工具涉及的代码是借鉴了其他帖子上的一部代码,结合本文作者项目的实际情况,编写而成。
输出EXCEL格式的测试用例文件
模板
测试用例使用如下模板输出,保存为XXX.xlsx文件,例如命名case.xlsx。
部分字段解释
功能点
一般EXCEL文件的一个Sheet页代表一个模块,在一个模块内部分为多个功能点,通过一个或多个测试用例对每个功能点进行一一覆盖,功能点字段就是对模块进行结构化划分的。
测试方式
该字段用以标识测试方式,是手工测试还是自动化测试,方便日后识别哪些用例是自动化实现的用例。
关键字
这个字段可以多种用途,例如用于识别产品形态,识别用例输出版本,或者用于识别质量属性,都是可以的。
作者项目中,是用于识别质量属性的,例如功能测试、性能测试、易用性测试等等。
重要性
填写P0/P1/P2,表示三个用例级别:高、中、低。
设计人员
该字段是用来标识用例的作者的,用于方便可追溯性或用例维护。
安装Python 3
由于本文中的EXCEL转换为xml的工具是用python语言写的,所以,首先需要安装python运行环境,本文中用的是3.6.2。
若已经安装了Python 3,则跳过此步骤。
下载安装python
Python3可以去网上免费下载安装,地址为:
https://www.python.org/ftp/python/3.6.2/python-3.6.2-amd64.exe
配置运行环境
安装完python后,配置环境变量。
我的电脑-》属性-》高级系统设置-》高级-》环境变量,在用户变量部分,找到变量名为path的,点击编辑、新建,将Python安装目录及pip所在目录都添加到环境变量表中,此例中为:\Python3d6\Python36\和F:\Python3d6\Python36\Scripts\。
具体的步骤在本文中就不赘述了,需要的可以自己去网上找。
调试python及pip
配置好环境变量后,就在CMD下运行python和pip,安装py脚本中涉及的python库。
但是作者在调试过程中,曾经遇到了如下的几个问题,供大家参考。
错误一
现象:
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\配置到环境变量中。
排查思路:
第一步,经初步判断,感觉是路径有问题。
随后,将安装路径改为F:\Python36\,即将“Python3d6”这层文件夹去掉,并重新配置环境变量。
现象:
Cmd命令行下,敲python正常,敲pip仍然后报错。
报错如下:
C:\Users\Administrator>pip install pywin32
Fatal error in launcher: Unable to create process using '"c:\python36\python3.exe" "F:\Python36\Scripts\pip.exe" install pywin32': ???????????
第二步,排除环境变量配置问题。
cd到安装目录下,执行pip,仍然报错。具体报错信息如下:
F:\Python36\Scripts>pip install pywin32
Fatal error in launcher: Unable to create process using '"c:\python36\python3.exe" "F:\Python36\Scripts\pip.exe" install pywin32': ???????????
第三步,尝试把python整个文件夹从F盘移动到C盘,然后修改好环境变量。
执行pip,没有报错,问题搞定,打印信息如下:
C:\Users\Administrator>pip
Usage:
pip <command> [options]
Commands:
install Install packages.
download Download packages.
uninstall Uninstall packages.
......
错误二
现象:
python运行.py文件报错 :NameError name 'reload' is not defined。
相关代码:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
原因:
setdefaultencoding是python2的sys库里边的函数,Python3的sys库里面已经没有 setdefaultencoding() 函数,并且Python3系统默认使用的就是utf-8编码。
解决方案:
将sys.setdefaultencoding("utf-8")代码整行去掉即可。
错误三
现象:调用print函数出错,具体报错信息如下:
C:\Users\Administrator>python3 F:\case\operate.py
File "F:\case\operate.py", line 46
print 'str=', str
^
SyntaxError: Missing parentheses in call to 'print'
原因:
python2.X版本与python3.X版本输出方式不同造成的。
解决方案:
Print函数后面加上括号()。
Python2代码与Python3代码不兼容
其实将python代码用python3执行,很多问题都是由于python2版本和python版本代码不兼容导致的。
下面以实际的例子,介绍一种python2代码转换成python3代码的方法。
假设:
python2.X到python3.X转换文件2to3.py的路径为C:\Python36\Tools\scripts。
待转换的文件operate.py的路径为D:\python2to3。
CMD下执行如下命令,即可将该python2文件转换为python3文件:
python3 C:\Python36\Tools\scripts\2to3.py -w D:\python2to3\operate.py
出现如下打印说明转换过程成功:
C:\Users\Administrator>python3 C:\Python36\Tools\scripts\2to3.py -w D:\python2to3\operate.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored D:\python2to3\operate.py
--- D:\python2to3\operate.py (original)
+++ D:\python2to3\operate.py (refactored)
@@ -1,7 +1,8 @@
# coding:utf-8
import os,re,xlrd
import sys
-reload(sys)
+import imp
+imp.reload(sys)
sys.setdefaultencoding("utf-8")
from easy_excel import easy_excel
@@ -43,7 +44,7 @@
def actions_add_div(str):
if str:
new_action_str=""
- print 'str=', str
+ print('str=', str)
for str_index in str.split('\n'):
newline=str_index + " " + "</div> " + "<div>" + " " + "</p> " + "<p>"
new_action_str+=newline
@@ -122,16 +123,16 @@
if __name__ == "__main__":
- print os.path.abspath('.')
+ print(os.path.abspath('.'))
excellist=[]
#列出当前目录下的所有.xml文件
for fullname in iterbrowse(os.path.abspath('.')):
- print fullname
+ print(fullname)
obj1=re.compile(r'([\W\w]*)(\.xlsx)#39;)
for m in obj1.finditer(fullname):
- print m.group()
+ print(m.group())
excellist.append(m.group())
- print excellist
+ print(excellist)
for fileName in excellist:
fileName=fileName.split('\\')[-1]
file_data = xlrd.open_workbook(fileName)
@@ -139,12 +140,12 @@
sheetList=[]
for index in range(sheetnum):
sheet_name=file_data.sheets()[index].name
- print sheet_name
+ print(sheet_name)
sheetList.append(sheet_name)
- print sheetList
+ print(sheetList)
for sheetName in sheetList:
test = operate(fileName, sheetName)
test.xlsx_to_dic(sheetName)
test.dic_to_xml(fileName, sheetName)
- print "Convert success!"
+ print("Convert success!")
os.system('pause')
RefactoringTool: Files that were modified:
RefactoringTool: D:\python2to3\operate.py
从日志中可以看出,转换过程中,对哪些行进行了修改一目了然。
如果某python文件不需要转换,则会出现如下的打印:
C:\Users\Administrator>python3 C:\Python36\Tools\scripts\2to3.py -w D:\python2to3\operate.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: No changes to D:\python2to3\operate.py
RefactoringTool: Files that need to be modified:
RefactoringTool: D:\python2to3\operate.py
将EXCEL转换为xml
安装好python库后,将用例表格与脚本放入同目录(脚本代码在文末),如下:
注意:用例表格的名称需用英文,不要含有中文。
cd到表格和脚本所在目录,然后运行 operate.py 文件,打印如下:
D:\python2to3>python3 operate.py
D:\python2to3
D:\python2to3\case.xlsx
D:\python2to3\case.xlsx
D:\python2to3\easy_excel.py
D:\python2to3\easy_excel.py.bak
D:\python2to3\operate.py
D:\python2to3\operate.py.bak
D:\python2to3\__pycache__\easy_excel.cpython-36.pyc
['D:\\python2to3\\case.xlsx']
XX功能模块1
XX功能模块2
['XX功能模块1', 'XX功能模块2']
('str=', '1.步骤一\n2.步骤二\n3.步骤三')
('str=', '1.步骤一\n2.步骤二\n3.步骤三')
Convert success!
请按任意键继续. . .
转换成功,按照EXCEL的sheet页输出两个XML文件:case.xlsx_XX功能模块1.xml和case.xlsx_XX功能模块2.xml,可以用来导入到Testlink用例管理系统中。
代码 easy_excel.py
# coding=utf-8
from xml.etree import ElementTree
from win32com.client import Dispatch
import win32com.client
import os
import sys
import imp
imp.reload(sys)
class easy_excel:
def __init__(self, filename=None):
self.xlApp = win32com.client.Dispatch('Excel.Application')
if filename:
self.filename = os.getcwd() + "\\" + filename
# self.xlApp.Visible=True
self.xlBook = self.xlApp.Workbooks.Open(self.filename)
else:
# self.xlApp.Visible=True
self.xlBook = self.xlApp.Workbooks.Add()
self.filename = ''
def save(self, newfilename=None):
if newfilename:
self.filename = os.getcwd() + "\\" + newfilename
# if os.path.exists(self.filename):
# os.remove(self.filename)
self.xlBook.SaveAs(self.filename)
else:
self.xlBook.Save()
def close(self):
self.xlBook.Close(SaveChanges=0)
self.xlApp.Quit()
def getCell(self, sheet, row, col):
sht = self.xlBook.Worksheets(sheet)
return sht.Cells(row, col).Value
def setCell(self, sheet, row, col, value):
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Value = value
# 设置居中
sht.Cells(row, col).HorizontalAlignment = 3
sht.Rows(row).WrapText = True
def mergeCells(self, sheet, row1, col1, row2, col2):
start_coloum = int(dic_config["start_coloum"])
# 如果这列不存在就不合并单元格
if col2 != start_coloum - 1:
sht = self.xlBook.Worksheets(sheet)
sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Merge()
# else:
# print 'Merge cells coloum %s failed!' %col2
def setBorder(self, sheet, row, col):
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Borders.LineStyle = 1
def set_col_width(self, sheet, start, end, length):
start += 96
end += 96
msg = chr(start) + ":" + chr(end)
# print msg
sht = self.xlBook.Worksheets(sheet)
sht.Columns(msg.upper()).ColumnWidth = length
operate.py
# coding:utf-8
import os,re,xlrd
import sys
import imp
imp.reload(sys)
from easy_excel import easy_excel
class operate():
def __init__(self, ExcelFileName, SheetName):
self.excelFile = ExcelFileName
self.excelSheet = SheetName
self.temp = easy_excel(self.excelFile)
self.dic_testlink = {}
self.row_flag = 2
self.testsuite = self.temp.getCell(self.excelSheet, 2, 2)
#print 'self.testsuite=',self.testsuite
self.dic_testlink[self.testsuite] = {"node_order": "13", "details": "", "testcase": []}
self.content = ""
self.content_list = []
def xlsx_to_dic(self, SheetName):
while True:
testcase = {"name": "", "node_order": "100", "externalid": "", "version": "1", "summary": "",
"preconditions": "", "execution_type": "1", "importance": "3", "steps": [], "keywords": "P1", "author":""}
testcase["name"] = self.temp.getCell(self.excelSheet, self.row_flag, 5)
testcase["summary"] = self.temp.getCell(self.excelSheet, self.row_flag, 3)
testcase["preconditions"] = self.temp.getCell(self.excelSheet, self.row_flag, 6)
execution_type = self.temp.getCell(self.excelSheet, self.row_flag, 9)
testcase["keywords"] = self.temp.getCell(self.excelSheet, self.row_flag, 10)
testcase["author"] = self.temp.getCell(self.excelSheet, self.row_flag, 11)
if execution_type == "自动":
testcase["execution_type"] = 2
step_number = 1
importance = self.temp.getCell(self.excelSheet, self.row_flag, 4)
if importance == "基本功能" or importance == "P1":
testcase["importance"]="2"
elif importance == "拓展" or importance == "P2":
testcase["importance"] = "1"
while True:
step = {"step_number": "", "actions": "", "expectedresults": "", "execution_type": ""}
step["step_number"] = step_number
step["actions"] = self.temp.getCell(self.excelSheet, self.row_flag, 7)
def actions_add_div(str):
if str:
new_action_str=""
print(('str=', str))
for str_index in str.split('\n'):
newline=str_index + " " + "</div> " + "<div>" + " " + "</p> " + "<p>"
new_action_str+=newline
return new_action_str[:-21]
step["actions"]=actions_add_div(step["actions"])
step["expectedresults"] = self.temp.getCell(self.excelSheet, self.row_flag, 8)
testcase["steps"].append(step)
step_number += 1
self.row_flag += 1
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:
break
# print testcase
self.dic_testlink[self.testsuite]["testcase"].append(testcase)
# print self.row_flag
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:
break
self.temp.close()
# print self.dic_testlink
def content_to_xml(self, key, value=None):
if key == 'step_number' or key == 'execution_type' or key == 'node_order' or key == 'externalid' or key == 'version' or key == 'importance':
return "<" + str(key) + "><![CDATA[" + str(value) + "]]></" + str(key) + ">"
elif key == 'actions' or key == 'expectedresults' or key == 'summary' or key == 'preconditions':
return "<" + str(key) + "><![CDATA[<div> " + str(value) + "</div> ]]></" + str(key) + ">"
elif key == 'keywords':
return '<keywords><keyword name="' + str(value) + '"><notes><![CDATA[ aaaa ]]></notes></keyword></keywords>'
elif key == 'name':
return '<testcase name="' + str(value) + '">'
elif key == 'author':
return '<custom_fields><custom_field><name><![CDATA[设计人员]]></name><value><![CDATA[%s]]></value></custom_field></custom_fields>' % str(value)
else:
return '##########'
def dic_to_xml(self, ExcelFileName, SheetName):
testcase_list = self.dic_testlink[self.testsuite]["testcase"]
for testcase in testcase_list:
for step in testcase["steps"]:
self.content += "<step>"
self.content += self.content_to_xml("step_number", step["step_number"])
self.content += self.content_to_xml("actions", step["actions"])
self.content += self.content_to_xml("expectedresults", step["expectedresults"])
self.content += self.content_to_xml("execution_type", step["execution_type"])
self.content += "</step>"
self.content = "<steps>" + self.content + "</steps>"
self.content = self.content_to_xml("importance", testcase["importance"]) + self.content
self.content = self.content_to_xml("execution_type", testcase["execution_type"]) + self.content
self.content = self.content_to_xml("preconditions", testcase["preconditions"]) + self.content
self.content = self.content_to_xml("summary", testcase["summary"]) + self.content
self.content = self.content_to_xml("version", testcase["version"]) + self.content
self.content = self.content_to_xml("externalid", testcase["externalid"]) + self.content
self.content = self.content_to_xml("node_order", testcase["node_order"]) + self.content
self.content = self.content + self.content_to_xml("keywords", testcase["keywords"])
self.content = self.content_to_xml("name", testcase["name"]) + self.content
self.content = self.content + self.content_to_xml("author", testcase["author"])
self.content = self.content + "</testcase>"
self.content_list.append(self.content)
self.content = ""
self.content = "".join(self.content_list)
self.content = '<testsuite name="' + self.testsuite + '">' + self.content + "</testsuite>"
self.content = '<?xml version="1.0" encoding="UTF-8"?>' + self.content
self.write_to_file(ExcelFileName, SheetName)
def write_to_file(self, ExcelFileName, SheetName):
xmlFileName = ExcelFileName + '_' + SheetName + '.xml'
cp = open(xmlFileName, "w")
cp.write(self.content)
cp.close()
#遍历某个文件目录下的所有文件名称
def iterbrowse(path):
for home, dirs, files in os.walk(path):
for filename in files:
yield os.path.join(home, filename)
if __name__ == "__main__":
print((os.path.abspath('.')))
excellist=[]
#列出当前目录下的所有.xml文件
for fullname in iterbrowse(os.path.abspath('.')):
print(fullname)
obj1=re.compile(r'([\W\w]*)(\.xlsx)#39;)
for m in obj1.finditer(fullname):
print((m.group()))
excellist.append(m.group())
print(excellist)
for fileName in excellist:
fileName=fileName.split('\\')[-1]
file_data = xlrd.open_workbook(fileName)
sheetnum=len(file_data.sheets())
sheetList=[]
for index in range(sheetnum):
sheet_name=file_data.sheets()[index].name
print(sheet_name)
sheetList.append(sheet_name)
print(sheetList)
for sheetName in sheetList:
test = operate(fileName, sheetName)
test.xlsx_to_dic(sheetName)
test.dic_to_xml(fileName, sheetName)
print("Convert success!")
os.system('pause')
**推荐一个「Python自动化测试学习交流群」给大家:
请关注+私信回复:"测试" 就可以免费拿到软件测试学习资料,同时进入群学习交流~~
相关推荐
- 墨尔本一华裔男子与亚裔男子分别失踪数日 警方寻人
-
中新网5月15日电据澳洲新快网报道,据澳大利亚维州警察局网站消息,22岁的华裔男子邓跃(Yue‘Peter’Deng,音译)失踪已6天,维州警方于当地时间13日发布寻人通告,寻求公众协助寻找邓跃。华...
- 网络交友须谨慎!美国犹他州一男子因涉嫌杀害女网友被捕
-
伊森·洪克斯克(图源网络,侵删)据美国广播公司(ABC)25日报道,美国犹他州一名男子于24日因涉嫌谋杀被捕。警方表示,这名男子主动告知警局,称其杀害了一名在网络交友软件上认识的25岁女子。雷顿警...
- 一课译词:来龙去脉(来龙去脉 的意思解释)
-
Mountainranges[Photo/SIPA]“来龙去脉”,汉语成语,本指山脉的走势和去向,现比喻一件事的前因后果(causeandeffectofanevent),可以翻译为“i...
- 高考重要考点:range(range高考用法)
-
range可以用作动词,也可以用作名词,含义特别多,在阅读理解中出现的频率很高,还经常作为完形填空的选项,而且在作文中使用是非常好的高级词汇。...
- C++20 Ranges:现代范围操作(现代c++白皮书)
-
1.引言:C++20Ranges库简介C++20引入的Ranges库是C++标准库的重要更新,旨在提供更现代化、表达力更强的方式来处理数据序列(范围,range)。Ranges库基于...
- 学习VBA,报表做到飞 第二章 数组 2.4 Filter函数
-
第二章数组2.4Filter函数Filter函数功能与autofilter函数类似,它对一个一维数组进行筛选,返回一个从0开始的数组。...
- VBA学习笔记:数组:数组相关函数—Split,Join
-
Split拆分字符串函数,语法Split(expression,字符,Limit,compare),第1参数为必写,后面3个参数都是可选项。Expression为需要拆分的数据,“字符”就是以哪个字...
- VBA如何自定义序列,学会这些方法,让你工作更轻松
-
No.1在Excel中,自定义序列是一种快速填表机制,如何有效地利用这个方法,可以大大增加工作效率。通常在操作工作表的时候,可能会输入一些很有序的序列,如果一一录入就显得十分笨拙。Excel给出了一种...
- Excel VBA入门教程1.3 数组基础(vba数组详解)
-
1.3数组使用数组和对象时,也要声明,这里说下数组的声明:'确定范围的数组,可以存储b-a+1个数,a、b为整数Dim数组名称(aTob)As数据类型Dimarr...
- 远程网络调试工具百宝箱-MobaXterm
-
MobaXterm是一个功能强大的远程网络工具百宝箱,它将所有重要的远程网络工具(SSH、Telnet、X11、RDP、VNC、FTP、MOSH、Serial等)和Unix命令(bash、ls、cat...
- AREX:携程新一代自动化回归测试工具的设计与实现
-
一、背景随着携程机票BU业务规模的不断提高,业务系统日趋复杂,各种问题和挑战也随之而来。对于研发测试团队,面临着各种效能困境,包括业务复杂度高、数据构造工作量大、回归测试全量回归、沟通成本高、测试用例...
- Windows、Android、IOS、Web自动化工具选择策略
-
Windows平台中应用UI自动化测试解决方案AutoIT是开源工具,该工具识别windows的标准控件效果不错,但是当它遇到应用中非标准控件定义的UI元素时往往就无能为力了,这个时候选择silkte...
- python自动化工具:pywinauto(python快速上手 自动化)
-
简介Pywinauto是完全由Python构建的一个模块,可以用于自动化Windows上的GUI应用程序。同时,它支持鼠标、键盘操作,在元素控件树较复杂的界面,可以辅助我们完成自动化操作。我在...
- 时下最火的 Airtest 如何测试手机 APP?
-
引言Airtest是网易出品的一款基于图像识别的自动化测试工具,主要应用在手机APP和游戏的测试。一旦使用了这个工具进行APP的自动化,你就会发现自动化测试原来是如此简单!!连接手机要进行...
- 【推荐】7个最强Appium替代工具,移动App自动化测试必备!
-
在移动应用开发日益火爆的今天,自动化测试成为了确保应用质量和用户体验的关键环节。Appium作为一款广泛应用的移动应用自动化测试工具,为测试人员所熟知。然而,在不同的测试场景和需求下,还有许多其他优...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)