2013-09-22 215 views
1

我是Python新手。我想从多个XML文件中检索标签值并将其打印在Excel表格中。我试过,并得到了除了Excel打印部分以外的脚本工作正常。在Excel中打印输出

这是我的脚本

from xml.dom.minidom import parse, parseString 
import xlwt 
import os 
def sh(dir): 
for r,d,f in os.walk(dir): 
    n=0 
    for files in f: 
     if files.endswith(".xml"): 
      print files 
      dom=parse(os.path.join(r, files)) 
      name = dom.getElementsByTagName('rev') 
      title = dom.getElementsByTagName('title') 
      a=xlwt.Workbook() 
      sheet=a.add_sheet('sheet1') 
      sheet.write(n, 0, files) 
      sheet.write(n, 1, title[0].firstChild.nodeValue) 
      sheet.write(n, 2, name[0].firstChild.nodeValue) 
      n=n+1 
      a.save('sha.xls') 
      print title[0].firstChild.nodeValue 
      print name[0].firstChild.nodeValue 

sh("path") 

我卡住了,则输出仅在这些列中打印的问题(0,0),(0,1),(0,2)。

例如如果我想

A   B   C 
D   E   F 
G   H   I 

我的输出

G   H   I 

(0,0),(0,1),(0,2)。 所以我明白,现有的每一个新的输出都被覆盖,只显示最终的输出。我怎样才能避免这一点,并得到我想要的?

回答

1

你应该定义你的工作簿和工作表外循环:

def sh(dir): 
    a = xlwt.Workbook() 
    sheet = a.add_sheet('sheet1') 
    n = 0 
    for r,d,f in os.walk(dir): 
     for files in f: 
      if files.endswith(".xml"): 
       print files 
       dom=parse(os.path.join(r, files)) 
       name = dom.getElementsByTagName('rev') 
       title = dom.getElementsByTagName('title') 
       sheet.write(n, 0, files) 
       sheet.write(n, 1, title[0].firstChild.nodeValue) 
       sheet.write(n, 2, name[0].firstChild.nodeValue) 
       n += 1 
       print title[0].firstChild.nodeValue 
       print name[0].firstChild.nodeValue 
    a.save('sha.xls') 

另外,如果你不需要搜索子目录里面的xml文件,可考虑改用glob.glob(),而不是使用os.walk()

def sh(dir): 
    a = xlwt.Workbook() 
    sheet = a.add_sheet('sheet1') 
    n = 0 
    for f in glob.glob(os.path.join(dir, '*.xml')): 
     dom = parse(os.path.join(dir, f)) 
     name = dom.getElementsByTagName('rev') 
     title = dom.getElementsByTagName('title') 
     sheet.write(n, 0, f) 
     sheet.write(n, 1, title[0].firstChild.nodeValue) 
     sheet.write(n, 2, name[0].firstChild.nodeValue) 
     n += 1 
    a.save('sha.xls') 
+0

非常感谢。它确实工作正常。我不知道glob.glob()格式,会尝试使用这个。再次感谢..:) –