以下是完整的代码:
import lxml.etree
import lxml.builder
import openpyxl
wb = openpyxl.load_workbook('C:\Users\powell.mittra\Excel.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
x = sheet.cell(row=12, column=1).value
E = lxml.builder.ElementMaker()
ROOT = E.x
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
我得到以下输出,其中' x'被视为字符串,而不是从x = sheet.cell(row = 12,column = 1)获取值.value:
<x>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</x>
有人可以告诉我是否可以传递ROOT中的值和excel表中的其他元素,或者使用LXML是不可能的?
答案 0 :(得分:1)
对于这些目标,我更喜欢使用xml.etree库。这是来自python标准库,所以你甚至不需要安装它。
import openpyxl
import xml.etree.ElementTree as ET
wb = openpyxl.load_workbook('C:\Users\powell.mittra\Excel.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
x = sheet.cell(row=12, column=1).value
root = ET.Element(x)
doc = ET.SubElement(root, "doc")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some value2"
tree = ET.ElementTree(root)
tree.write("filename.xml")
但是如果你想使用lxml,你可以在最后改变标签
import lxml.etree
import lxml.builder
import openpyxl
wb = openpyxl.load_workbook('C:\Users\powell.mittra\Excel.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
x = sheet.cell(row=12, column=1).value
E = lxml.builder.ElementMaker()
ROOT = E.x
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
the_doc.tag = x
print lxml.etree.tostring(the_doc, pretty_print=True)