【问题标题】:Converting excel to xml with Null values in excel在excel中将excel转换为带有Null值的xml
【发布时间】:2021-07-27 13:59:54
【问题描述】:

我正在尝试使用此框架代码将 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)

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

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] 为空时,它应该像我的xml 结果文件中的&lt;usernumber&gt;&lt;/usernumber&gt;

我该怎么做?

【问题讨论】:

  • 请提供完整的回溯。
  • 您好,我也添加了回溯。谢谢。
  • 尝试检查None并在这种情况下添加“”。您还可以在标签名称和单元格值上使用“zip()”。

标签: python openpyxl yattag


【解决方案1】:

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

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

因此,如果服务代码为空,则结果为:&lt;serviceareacode&gt;&lt;/serviceareacode&gt; 如果不为空,则结果为:&lt;serviceareacode&gt;value&lt;/serviceareacode&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多