您可以使用以下代码将树形表格的序号导出为Excel文件:

import openpyxl

def export_tree_to_xlsx(tree, filename):
    wb = openpyxl.Workbook()
    ws = wb.active
    
    # 递归遍历树形表格
    def traverse(node, level, parent_index):
        nonlocal ws
        nonlocal filename

        # 获取当前节点的序号
        index = parent_index + [str(node['index'])]

        # 将序号转换为字符串,如 "1.1.1.1"
        index_str = '.'.join(index)

        # 将序号写入Excel表格
        ws.append([index_str])

        # 将子节点写入Excel表格
        for child in node['children']:
            traverse(child, level + 1, index)
    
    traverse(tree, 1, [])

    # 保存Excel文件
    wb.save(filename)

# 示例树形表格数据
tree = {
    'index': 1,
    'children': [
        {
            'index': 1,
            'children': [
                {
                    'index': 1,
                    'children': []
                },
                {
                    'index': 2,
                    'children': []
                }
            ]
        },
        {
            'index': 2,
            'children': [
                {
                    'index': 1,
                    'children': []
                },
                {
                    'index': 2,
                    'children': [
                        {
                            'index': 1,
                            'children': []
                        },
                        {
                            'index': 2,
                            'children': []
                        }
                    ]
                }
            ]
        }
    ]
}

# 导出树形表格到Excel文件
export_tree_to_xlsx(tree, 'tree.xlsx')

请注意,此代码使用openpyxl库来创建并操作Excel文件。您可以根据需要对代码进行修改,例如更改导出的单元格位置、样式等


原文地址: http://www.cveoy.top/t/topic/hP2o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录