0

我正在尝试使用此框架代码将 excel 文件转换为 xml:

wb = load_workbook("deneme.xlsx")
# Getting an object of active sheet 1
ws = wb.worksheets[0]
doc, tag, text = Doc().tagtext()

xml_header = '<?xml version="1.0" encoding="UTF-8"?>'

# Appends the String to document
doc.asis(xml_header)
with tag('userdata'):
    with tag('basicinf'):
        for row in ws.iter_rows(min_row=2, max_row=None, min_col=1, max_col=90):
            row = [cell.value for cell in row]
            a=row[0]


            with tag("usernumber"):
                text(row[0])

            with tag("username"):

                text(row[1])
            with tag("serviceareacode"):
                text(row[2])
            with tag("language"):
                text(row[3])
            with tag("welcomemsgid"):
                text(row[4])
            with tag("calledlimitedid"):
                text(row[5])
            with tag("followmeflag"):
                text(row[6])
            with tag("followmenumber"):
                text(row[7])
            with tag("mobilespecial"):
                text(row[8])
result = indent(
    doc.getvalue(),
    indentation='  ',
    indent_text=False
)

print(result)
with open("routescheme_{}.xml".format(a), "w") as f:
    f.write(result)

现在,如果我不在row[0]excel 中写任何输入,我会收到以下错误:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 489, in html_escape
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
AttributeError: 'NoneType' object has no attribute 'replace'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\abdul\Desktop\mmm\main.py", line 36, in <module>
    text(row[0])
  File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 179, in text
    transformed_string = html_escape(strg)
  File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 491, in html_escape
    raise TypeError(
TypeError: You can only insert a string, an int or a float inside a xml/html text node. Got None (type <class 'NoneType'>) instead.

我的期望是,当row[0]它为空时,它应该像<usernumber></usernumber>我的 xml 结果文件中一样。

我怎样才能做到这一点?

4

1 回答 1

0

我想我自己找到了解决方案。我不确定这是一个好的解决方案,但是,

            with tag("usernumber"):
            if (row[0] == None):
                text()
            else:
             text(row[0])

因此,如果 serviceare 代码为空,则结果为:<serviceareacode></serviceareacode> 如果不为空,则结果为:<serviceareacode>value</serviceareacode>

于 2021-07-27T17:48:24.697 回答