Python Openpyxl 追加问题

Python Openpyxl Append issue

我有数百个 XML 文件,我需要从中提取两个值并输出到 Excel 或 CSV 文件中。这是我目前拥有的代码:

#grabs idRoot and typeId root values from XML files
import glob
from openpyxl import Workbook
from xml.dom import minidom
import os


wb = Workbook()
ws = wb.active
def typeIdRoot (filename):

    f = open(filename, encoding = "utf8")
    for xml in f:

        xmldoc = minidom.parse(f)

        qmd = xmldoc.getElementsByTagName("MainTag")[0]

        typeIdElement = qmd.getElementsByTagName("typeId")[0]

        root = typeIdElement.attributes["root"]

        global rootValue
        rootValue = root.value
    print ('rootValue =' ,rootValue,)
    ws.append([rootValue])
    wb.save("some.xlsx")   



wb = Workbook()
ws = wb.active
def idRoot (filename):

    f = open(filename, encoding = "utf8")
    for xml in f:

        xmldoc = minidom.parse(f)

        tcd = xmldoc.getElementsByTagName("MainTag")[0]

        activitiesElement = tcd.getElementsByTagName("id")[0]

        sport = activitiesElement.attributes["root"]

        sportName = sport.value

        print ('idRoot =' ,sportName,)

        ws.append([idRoot])

        wb.save("some.xlsx")    


for file in glob.glob("*.xml"):
    typeIdRoot (file)

for file in glob.glob("*.xml"):
    idRoot (file)


第一个值遵循 1.11.111.1.111111.1.3 格式。第二个混合字母和数字。我相信这是错误的原因:

Traceback (most recent call last):
  File "C:\Python34\Scripts\xml\good.py", line 64, in <module>
    idRoot (file)
  File "C:\Python34\Scripts\xml\good.py", line 54, in idRoot
    ws.append([idRoot])
  File "C:\Python34\lib\site-packages\openpyxl\worksheet\worksheet.py", line 754, in append
    cell = self._new_cell(col, row_idx, content)
  File "C:\Python34\lib\site-packages\openpyxl\worksheet\worksheet.py", line 376, in _new_cell
    cell = Cell(self, column, row, value)
  File "C:\Python34\lib\site-packages\openpyxl\cell\cell.py", line 131, in __init__
    self.value = value
  File "C:\Python34\lib\site-packages\openpyxl\cell\cell.py", line 313, in value
    self._bind_value(value)
  File "C:\Python34\lib\site-packages\openpyxl\cell\cell.py", line 217, in _bind_value
    raise ValueError("Cannot convert {0} to Excel".format(value))
ValueError: Cannot convert <function idRoot at 0x037D24F8> to Excel


我希望结果将两个值添加到同一行。那么我将为目录中的每个文件创建一个新行。我需要将第二个值添加到第二行。

这样:

  Value 1                           Value 2
1.11.111.1.111111.1.3           10101011-0d10-0101-010d-0dc1010e0101

idRoot 是您的 FUNCTION 的名称。 所以当你写

ws.append([idRoot])

你的意思可能是:

ws.append([sportName])

当然你可以这样写:

ws.append([rootValue, sportName])

前提是两个变量都定义了合理的值。 最后一件事,您应该只保存一次文件。