百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

技术干货丨Python轻松实现EXCEL转XML,项目实战

yuyutoo 2024-10-12 01:55 3 浏览 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自动化测试学习交流群」给大家:

请关注+私信回复:"测试" 就可以免费拿到软件测试学习资料,同时进入群学习交流~~

相关推荐

野路子科技!2步教你把手机改造成一个FTP服务器,支持PC互传

哈喽,大家好,我是野路子科技,今天来给大家带来一个教程,希望大家喜欢。正如标题所言,就是教大家如何把售价改造成FTP服务器,而这个时候估计有朋友会问了,把手机改造成FTP服务器有什么用呢?现在有Q...

不得不看:别样于Server-U的群晖文件存储服务器的搭建与使用

我先前的作品中,有着关于Server-U的ftp文件存储服务器的搭建与访问的头条文章和西瓜视频,而且我们通过各种方式也给各位粉丝介绍了如何突破局域网实现真正意义上的公网访问机制技术。关于Server-...

Qt三种方式实现FTP上传功能_qt引入qftp库

FTP协议FTP的中文名称是“文件传输协议”,是FileTransferProtocol三个英文单词的缩写。FTP协议是TCP/IP协议组中的协议之一,其传输效率非常高,在网络上传输大的文件时,经...

Filezilla文件服务器搭建及客户端的使用

FileZilla是一个免费开源的FTP软件,分为客户端版本和服务器版本,具备所有的FTP软件功能。可控性、有条理的界面和管理多站点的简化方式使得Filezilla客户端版成为一个方便高效的FTP客户...

美能达柯美/震旦复印机FTP扫描怎么设置?

好多网友不知道怎么安装美能达/震旦复印机扫描,用得最多是SMB和FTP扫描,相对于SMB来说,FTP扫描安装步骤更为便捷,不容易出问题,不需要设置文件夹共享,所以小编推荐FTP来扫描以美能达机器为例详...

CCD(简易FTP服务器软件)_简单ftp服务器软件

CCD简易FTP服务器软件是一款很方便的FPT搭建工具,可以将我们的电脑快速变成一个FPT服务器。使用方法非常简单,只要运行软件就会自动生效,下载银行有该资源。该工具是不提供操作界面的,其他用户可以输...

Ubuntu系统搭建FTP服务器教程_ubuntu架设服务器

在Ubuntu系统上搭建FTP服务器是文件传输的一个非常实用方法,适合需要进行大量文件交换的场景。以下是一步步指导,帮助您在Ubuntu上成功搭建FTP服务器。1.安装vsftpd软件...

理光FTP扫描设置教程_理光ftp扫描设置方法

此教程主要用来解决WIN10系统下不能使用SMB文件夹扫描的问题,由于旧的SMB协议存在安全漏洞,所以微软在新的系统,WIN8/WIN10/SERVER201220162018里使用了新的SMB传...

纯小白如何利用wireshark学习网络技术

写在前面工欲善其事必先利其器!熟悉掌握一种神器对以后的工作必然是有帮助的,下面我将从简单的描述Wireshark的使用和自己思考去写,若有错误或不足还请批评指正。...

京东买13盘位32GB内存NAS:NAS系统安装设置教程

本内容来源于@什么值得买APP,观点仅代表作者本人|作者:yasden你没有看错,我在京东自营商城购买硬件,组装了一台13盘位,32GB内存的NAS,硬盘有13个盘位!CPU是AMD的5500!本文...

FileZilla搭建FTP服务器图解教程_filezilla server搭建ftp服务器

...

python教程之FTP相关操作_python ftps

ftplib类库常用相关操作importftplibftp=ftplib.FTP()ftp.set_debuglevel(2)#打开调试级别2,显示详细信息ftp.connect(“I...

xftp怎么用,xftp怎么用,具体使用方法

Xftp是一款界面化的ftp传输工具,用起来方便简单,这里为大家分享下Xftp怎么使用?希望能帮到有需要的朋友。IIS7服务器管理工具可以批量管理、定时上传下载、同步操作、数据备份、到期提醒、自动更新...

树莓派文件上传和下载,详细步骤设置FTP服务器

在本指南中,详细记录了如何在树莓Pi上设置FTP。设置FTP可以在网络上轻松地将文件传输到Pi上。FTP是文件传输协议的缩写,只是一种通过网络在两个设备之间传输文件的方法。还有一种额外的方法,你可以用...

win10电脑操作系统,怎么设置FTP?windows10系统设置FTP操作方法

打印,打印,扫描的日常操作是每一个办公工作人员的必需专业技能,要应用FTP作用扫描文件到电脑上,最先要必须一台可以接受文件的FTP服务器。许多软件都需要收费标准进行,但人们还可以应用Windows的系...

取消回复欢迎 发表评论: