使用Python3将manifest.xml转为excel供查看

#!/usr/bin/env python3

from xml.dom.minidom import parse
import xml.dom.minidom
import os,os.path
import xlwt
import sys, getopt

#存放所有数据,二位数据,到时候将次二维数组数据直接写入excel中
projectsExcel=[]
projectsExcel.append(['Manifest','工程名称','仓库地址','分支'])

def usage():
    print('ManifestParse.py usage:')
    print('-i:      指定Manifest存放的文件夹')

#数据写入xls
def write_to_excel(excelFileName,sheetName,data):
    '''Write content to a new excel'''
    new_workbook=xlwt.Workbook()
    newSheet=new_workbook.add_sheet(sheetName)
    i=j=0
    for x in range(0,len(data)):
        for y in data[i]:
            newSheet.write(i,j,y)
            j+=1
        i+=1
        j=0
    if not os.path.exists('parse_results'):
        os.makedirs('parse_results')
    new_workbook.save(r'parse_results/'+excelFileName+'.xls')

def parse_manifest(manifestName,manifestPath):
    # 使用minidom解析器打开 XML 文档
    DOMTree = xml.dom.minidom.parse(manifestPath)
    collection = DOMTree.documentElement
    remotes = collection.getElementsByTagName("remote")

    remoteDict={}
    for remote in remotes:
        remoteDict[remote.getAttribute('name')]=remote.getAttribute('fetch')

    default = collection.getElementsByTagName("default")[0]
    #默认远程地址
    defaultRemote=remoteDict.get(default.getAttribute('remote'))
    #默认分支
    defaultRevision=default.getAttribute('revision')
    #获取所有的project属性
    projects = collection.getElementsByTagName("project")
    for x in projects:
        #获取工程名
        projectName = x.getAttribute('name')
        #获取工程地址
        projectRemoteKey=x.getAttribute('remote')
        if projectRemoteKey ==None:
            projectRemoteKey=default.getAttribute('remote')
        projectRemote=remoteDict.get(projectRemoteKey)
        if projectRemote==None:
            projectRemote=defaultRemote
        #获取工程分支
        projectBranch=x.getAttribute('revision')
        if projectBranch =='':
            projectBranch=defaultRevision
        #应用分支数据追加到总的数据文件上
        one=[manifestName,projectName,projectRemote+'/'+projectName,projectBranch]
        projectsExcel.append(one)
        print(manifestName,' ',projectName,'  ',projectRemote+'/'+projectName,' ',projectBranch)

def main(manifestDir):
    for root, dirs, files in os.walk(manifestDir,topdown=False):
        for name in files:
            path = os.path.join(root,name)
            if path.endswith('xml'):
                print(path)
                parse_manifest(name,path)
     #统计结果写入excel
    write_to_excel('统计结果','应用分支详情',projectsExcel)

if __name__ == '__main__':
    manifestDir=None
    try:
      opts, args = getopt.getopt(sys.argv[1:],'i:')
    except getopt.GetoptError:
      usage()
      sys.exit(2)
    for o,a in opts:
        print(o,a)
        if o == '-i':
            manifestDir=a
    if manifestDir == None:
        usage()
    else:
        main(manifestDir)

你可能感兴趣的:(python,python,excel)