栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 根据树型结构生成指定格式的excel数据

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 根据树型结构生成指定格式的excel数据

数据
tree = {
    'a': {
        'a1': [('a1a', 1)],
        'a2': [
                ('a2a', 1),
                ('a2b', 2),
               ]
    },
    'b': {
        'b1': [('b1b', 1)],
        'b2': [('b2b', 1)]
    }
}
excel 数据格式

代码实现
import xlrd
from xlutils.copy import copy

old_excel = xlrd.open_workbook('1.xls')
new_excel = copy(old_excel)
ws = new_excel.get_sheet(0)

def write_tree_to_excel(tree, start_col=0, start_row=0):
    if isinstance(tree, dict):
        lines = 0
        row = start_row
        for k, item in tree.items():
            lines += write_tree_to_excel(item, start_col+1, start_row)
            end_row = row+lines
            print(start_col*'t', k, ':', start_row, end_row, start_col)
            ws.write_merge(start_row, end_row-1, start_col, start_col)
            ws.write(start_row, start_col, k)
            start_row = end_row
        return lines

    elif isinstance(tree, list):
        row = start_row
        for item in tree:
            print(start_col*'t', item[0], ':', row, start_col)
            ws.write(row, start_col, item[0])
            row += 1
        return len(tree)
 
write_tree_to_excel(tree)
new_excel.save('2.xls')
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/840253.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号