Write a self-defined class type data to excel using xlsxwriter TypeError: Unsupported type <class '__main__.node'> in write()

Write a self-defined class type data to excel using xlsxwriter TypeError: Unsupported type <class '__main__.node'> in write()

我正在使用 xlsxwriter 将自定义类型的数据写入 excel 文件,但出现错误:

TypeError: Unsupported type <class '__main__.node'> in write()

代码:

import xlsxwriter

class node(object):
    def __init__(self, value):
        self.value = value
        self.children = []
    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret
    def add(self, nod):
        self.children.append(node(nod))
        
leaf_1 = ['AA','BB','CC','DD']


workbook = xlsxwriter.Workbook('print_def.xlsx')
worksheet = workbook.add_worksheet()    

tree = parent = node(leaf_1[0]) #### code 1
parent.add(leaf_1[1])
parent.add(leaf_1[2])
print(tree)
worksheet.write(1, 0, tree)

预期结果(将带缩进空格的tree放在特定单元格中):

问题:

有没有人有过这个错误的经验?或建议?提前致谢!

更新:

我在 print(tree) 之后添加了以下部分,而不是使用 worksheet.write(1, 0, tree)

def write_node(worksheet, row, col, tree, format = None):
    return worksheet.write_string(row, col, str(tree), format)
worksheet.add_write_handler(tree.children, write_node)
# worksheet.add_write_handler(tree.node, write_node)
worksheet.write('A1', tree)

但是,报错如下:

Traceback (most recent call last):
  File "/Users.../pythonProject/2021-05-16.py", line 137, in <module>
    worksheet.add_write_handler(tree.children, write_node)
  File "/Users.../pythonProject/lib/python3.9/site-packages/xlsxwriter/worksheet.py", line 1365, in add_write_handler
    self.write_handlers[user_type] = user_function
TypeError: unhashable type: 'list'

XlsxWriter 不会写入任意数据类型,因此 class 中的 __repr__ 将被忽略。

如果您想编写用户定义的类型,您将需要使用 Xlsxwriter add_write_handler() 机制。请参阅 Writing user defined types 上的 XlsxWriter 文档。它有详细的解释和几个例子。

另请注意,您应该首先验证您是否可以 Excel 以您想要的方式显示数据。您至少需要添加文本环绕格式。

更新。这是一个基于您的代码的小型工作示例:

import xlsxwriter


class node(object):
    def __init__(self, value):
        self.value = value
        self.children = []

    def __repr__(self, level=0):
        ret = "    " * level + repr(self.value) + "\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret

    def add(self, nod):
        self.children.append(node(nod))


def write_node(worksheet, row, col, tree, format=None):
    return worksheet.write_string(row, col, str(tree), format)

workbook = xlsxwriter.Workbook('print_def.xlsx')
worksheet = workbook.add_worksheet()

text_wrap = workbook.add_format({'text_wrap': True})

worksheet.add_write_handler(node, write_node)

leaf_1 = ['AA', 'BB', 'CC', 'DD']
tree = parent = node(leaf_1[0])
parent.add(leaf_1[1])
parent.add(leaf_1[2])

worksheet.write(0, 0, tree, text_wrap)

workbook.close()

输出:

注意,我用 4 个空格替换了“\t”,因为它在 Excel 中显示得更好。此外,您还需要添加文字环绕格式,如图所示。