Python实现将xml导入至excel


Posted in Python onNovember 20, 2015

最近在使用Testlink时,发现导入的用例是xml格式,且没有合适的工具转成excel格式,xml使用excel打开显示的东西也太多,网上也有相关工具转成csv格式的,结果也不合人意。

那求人不如尔己,自己写一个吧

需要用到的模块有:xml.dom.minidom(python自带)、xlwt

使用版本:

python:2.7.5

xlwt:1.0.0

一、先分析Testlink XML格式:

Python实现将xml导入至excel

这是一个有两级testusuit的典型的testlink用例结构,我们只需要取testsuite name,testcase name,preconditions,actions,expectedresults

二、程序如下:

#coding:utf-8
'''
Created on 2015-8-20

@author: Administrator
'''
'''
'''
import xml.etree.cElementTree as ET
import xml.dom.minidom as xx
import os,xlwt,datetime

workbook=xlwt.Workbook(encoding="utf-8")
# 
booksheet=workbook.add_sheet(u'sheet_1')
booksheet.col(0).width= 5120
booksheet.col(1).width= 5120
booksheet.col(2).width= 5120
booksheet.col(3).width= 5120
booksheet.col(4).width= 5120
booksheet.col(5).width= 5120

dom=xx.parse(r'D:\\Python27\test.xml')
root = dom.documentElement
row=1
col=1

borders=xlwt.Borders()
borders.left=1
borders.right=1
borders.top=1
borders.bottom=1


style = xlwt.easyxf('align: wrap on,vert centre, horiz center') #自动换行、水平居中、垂直居中
#设置标题的格式,字体方宋、加粗、背景色:菊黄
#测试项的标题

title=xlwt.easyxf(u'font:name 仿宋,height 240 ,colour_index black, bold on, italic off; align: wrap on, vert centre, horiz center;pattern: pattern solid, fore_colour light_orange;')
item='测试项'
Subitem='测试分项'
CaseTitle='测试用例标题'
Condition='预置条件'
actions='操作步骤'
Result='预期结果'
booksheet.write(0,0,item,title)
booksheet.write(0,1,Subitem,title)
booksheet.write(0,2,CaseTitle,title)
booksheet.write(0,3,Condition,title)
booksheet.write(0,4,actions,title)
booksheet.write(0,5,Result,title)
#冻结首行
booksheet.panes_frozen=True
booksheet.horz_split_pos= 1


#一级目录
for i in root.childNodes:
  testsuite=i.getAttribute('name').strip()
  #print testsuite
  #print testsuite
  '''
  写测试项
  '''
  print "row is :",row
  booksheet.write(row,col,testsuite,style)
  

  #二级目录
  for dd in i.childNodes:
    print "    %s" % dd.getAttribute('name')
    testsuite2=dd.getAttribute('name')
    if not dd.getElementsByTagName('testcase'):
      print "Testcase is %s" % testsuite2
      row=row+1
      booksheet.write(row,2,testsuite2,style)  #写测试分项
    
    row=row+1
    
    booksheet.write(row,1,testsuite2,style)
    itemlist=dd.getElementsByTagName('testcase')
    
    for subb in itemlist:
      #print "         %s" % subb.getAttribute('name')
      testcase=subb.getAttribute('name')
      
      row=row+1
      booksheet.write(row,2,testcase,style)

      ilist=subb.getElementsByTagName('preconditions')
      for ii in ilist:
        preconditions=ii.firstChild.data.replace("<br />"," ")
        col=col+1
        booksheet.write(row,3,preconditions,style)
      steplist=subb.getElementsByTagName('actions')
      #print steplist
      for step in steplist:
        actions=step.firstChild.data.replace("<br />"," ")
        col=col+1
        booksheet.write(row,4,actions,style)
      #print "测试步骤:",steplist[0].firstChild.data.replace("<br />"," ")
      expectlist=subb.getElementsByTagName('expectedresults')
      
      for expect in expectlist:
        result=expect.childNodes[0].nodeValue.replace("<br />","" )
        booksheet.write(row,5,result,style)

      
  row=row+1
        
workbook.save('demo.xls')

写入excel的效果如下:

Python实现将xml导入至excel

我们再来看个实例:

需要下载一个module:xlwt,如下是source code

import xml.dom.minidom
import xlwt
import sys

col = 0
row = 0  


def handle_xml_report(xml_report, excel):  
  problems = xml_report.getElementsByTagName("problem")
  handle_problems(problems, excel)
  

def handle_problems(problems, excel):
  for problem in problems:
    handle_problem(problem, excel)


def handle_problem(problem, excel):
  global row
  global col
  code = problem.getElementsByTagName("code")  
  file = problem.getElementsByTagName("file")  
  line = problem.getElementsByTagName("line")  
  message  = problem.getElementsByTagName("message")

  for node in code:  
    excel.write(row, col, node.firstChild.data)
    col = col + 1 
  for node in file:  
    excel.write(row, col, node.firstChild.data) 
    col = col + 1    
  for node in line:  
    excel.write(row, col, node.firstChild.data)     
    col = col + 1    
  for node in message:  
    excel.write(row, col, node.firstChild.data)     
    col = col + 1
  row = row+1
  col = 0

if __name__ == '__main__': 
  if(len(sys.argv) <= 1):
    print ("usage: xml2xls src_file [dst_file]")
    exit(0)
  #the 1st argument is XML report ; the 2nd is XLS report
  if(len(sys.argv) == 2):
    xls_report = sys.argv[1][:-3] + 'xls'
  #if there are more than 2 arguments, only the 1st & 2nd make sense
  else:
    xls_report = sys.argv[2]
  xmldoc = xml.dom.minidom.parse(sys.argv[1]) 
  wb = xlwt.Workbook()
  ws = wb.add_sheet('MOLint')
  ws.write(row, col, 'Error Code')
  col = col + 1
  ws.write(row, col, 'file')
  col = col + 1  
  ws.write(row, col, 'line')  
  col = col + 1  
  ws.write(row, col, 'Description') 
  row = row + 1
  col = 0
  handle_xml_report(xmldoc, ws)
  wb.save(xls_report)
Python 相关文章推荐
Python中bisect的用法
Sep 23 Python
Python的面向对象思想分析
Jan 14 Python
彻底理解Python list切片原理
Oct 27 Python
Python实现mysql数据库更新表数据接口的功能
Nov 19 Python
Python爬虫信息输入及页面的切换方法
May 11 Python
python使用matplotlib画饼状图
Sep 25 Python
matlab中imadjust函数的作用及应用举例
Feb 27 Python
Python参数传递及收集机制原理解析
Jun 05 Python
python设置表格边框的具体方法
Jul 17 Python
Python如何实现大型数组运算(使用NumPy)
Jul 24 Python
Python关于拓扑排序知识点讲解
Jan 04 Python
如何用 Python 子进程关闭 Excel 自动化中的弹窗
May 07 Python
使用PyCharm配合部署Python的Django框架的配置纪实
Nov 19 #Python
详解在Python程序中解析并修改XML内容的方法
Nov 16 #Python
Python通过DOM和SAX方式解析XML的应用实例分享
Nov 16 #Python
Python的Flask开发框架简单上手笔记
Nov 16 #Python
python实现mysql的单引号字符串过滤方法
Nov 14 #Python
浅析Python中signal包的使用
Nov 13 #Python
Python下rrdtool模块的基本使用方法
Nov 13 #Python
You might like
全国FM电台频率大全 - 25 云南省
2020/03/11 无线电
thinkphp配置连接数据库技巧
2014/12/02 PHP
Symfony实现行为和模板中取得request参数的方法
2016/03/17 PHP
PHP实现对文件锁进行加锁、解锁操作的方法
2017/07/04 PHP
thinkPHP中钩子的使用方法实例分析
2017/11/16 PHP
ThinkPHP 5.1 跨域配置方法
2019/10/11 PHP
『JavaScript』限制Input只能输入数字实现思路及代码
2013/04/22 Javascript
使用mini-define实现前端代码的模块化管理
2014/12/25 Javascript
js绘制圆形和矩形的方法
2015/08/05 Javascript
详解js中class的多种函数封装方法
2016/01/03 Javascript
百度地图API之百度地图退拽标记点获取经纬度的实现代码
2017/01/12 Javascript
详解AngularJS ui-sref的简单使用
2017/04/24 Javascript
angular.js指令中transclude选项及ng-transclude指令详解
2017/05/24 Javascript
ES6中的Promise代码详解
2017/10/09 Javascript
jQuery实现打开网页自动弹出遮罩层或点击弹出遮罩层功能示例
2017/10/19 jQuery
使用async await 封装 axios的方法
2018/07/09 Javascript
python读取csv文件示例(python操作csv)
2014/03/11 Python
Python MySQLdb模块连接操作mysql数据库实例
2015/04/08 Python
Python HTMLParser模块解析html获取url实例
2015/04/08 Python
python使用筛选法计算小于给定数字的所有素数
2018/03/19 Python
python实现全盘扫描搜索功能的方法
2019/02/14 Python
nginx黑名单和django限速,最简单的防恶意请求方法分享
2019/08/09 Python
python绘制雪景图
2019/12/16 Python
Python内置函数locals和globals对比
2020/04/28 Python
StubHub意大利:购买和出售全球演唱会和体育赛事门票
2017/11/21 全球购物
草莓网中国:StrawberryNet中国
2020/08/17 全球购物
学生宿舍管理制度
2014/01/30 职场文书
爱心活动计划书
2014/04/26 职场文书
小学班主任培训方案
2014/06/04 职场文书
社区服务活动报告
2015/02/05 职场文书
党员廉洁自律个人总结
2015/02/13 职场文书
部门经理迟到检讨书
2015/02/16 职场文书
2016年小学生迎国庆广播稿
2015/12/18 职场文书
Nginx+SpringBoot实现负载均衡的示例
2021/03/31 Servers
看完这篇文章获得一些java if优化技巧
2021/07/15 Java/Android
一文了解MYSQL三大范式和表约束
2022/04/03 MySQL