如何利用python将xmind转为Excel?

1.环境准备

需要先安装xmindparser模块,安装方法较为简单,直接运行pip命令即可。

pip install xmindparser

2.源数据构造及流程解析

2.1 准备xmind文件

构建好xmind文件后,将其命名为test.xmind,其图像如下:
2.1

2.2 解析xmind文件

利用xmindparser对2.1中的xmind文件进行解析,解析后效果如下:
2.2
解析代码如下:

from xmindparser import xmind_to_dict
x_flie = r'Test.xmind'
json_data= xmind_to_dict(x_flie)
2.3 对解析后的数据进行处理

由于解析后的数据不符合写出的要求,故需要对这部分数据进行处理。由于本人喜欢用pandas进行数据处理,故在此构建dataframe进行输出。

2.3.1 处理1——提取数据

对2.2中解析后的数据进行处理,按照层次进行组合,得到效果如下的数据:
2.3.1
实现代码如下:

# 可以设想为一个树结构,利用递归函数,获取由根至各叶子节点的路径。
def xm_parse(dic, pre_data=[]):
    """输入一个由xmindparser,转换而来的字典形式的数据,将之转换成列表"""
    title_list = []
    topic_list = []
    try:
        topics = dic.get("topics")
        title = dic.get("title")
        # 将前缀追加
        title_list.append(title)
        title_list = pre_data + title_list
        # 如果到达末尾,就返回
        if topics is None and title:
            yield title, title_list
#             print(title,title_list)
            return
        # 如果是列表,就暂存起来(若每个对象为标准的列表,即 topics= topic_list,则可以跳过该步骤)
        elif isinstance(topics, list) and title:
            for topic in topics:
                topic_list.append(topic)
    except AttributeError as e:
        print("异常结束")
        return
    # 若列表不为空,则需要递归寻找
    if topic_list:
        for topic in topic_list:
            yield from xm_parse(topic,title_list)
2.3.2 处理2——填充数据

经2.3.1的过程处理后的数据,并不能直接作为参数直接转换为DataFrame,需要将数据处理成以下形式:
2.3.2
实现代码如下:

temp=[]
max_cols=0
#提取数据,并找出最大深度(列数)
for i,j in xm_parse(json_data[0]['topic']):
    temp.append(j)
    max_cols= max_cols if max_cols > len(j) else len(j)
#对缺失数据采用补全
for i in range(len(temp)):
    temp[i] = temp[i] + (max_cols - len(temp[i])) * [None]
2.3.3 处理3——转换成DataFrame

转换后,效果如下:
2.3.3

实现代码如下:

result=pd.DataFrame.from_records(temp,columns=["标题-{}".format(i+1) for i in range(max_cols)])

3.完整代码

from xmindparser import xmind_to_dict
import pandas as pd

# 可以设想为一个树结构,利用递归函数,获取由根至各叶子节点的路径。
def xm_parse(dic, pre_data=[]):
    """输入一个由xmindparser,转换而来的字典形式的数据,将之转换成列表"""
    title_list = []
    topic_list = []
    try:
        topics = dic.get("topics")
        title = dic.get("title")
        # 将前缀追加
        title_list.append(title)
        title_list = pre_data + title_list
        # 如果到达末尾,就返回
        if topics is None and title:
            yield title, title_list
#             print(title,title_list)
            return
        # 如果是列表,就暂存起来(若每个对象为标准的列表,即 topics= topic_list,则可以跳过该步骤)
        elif isinstance(topics, list) and title:
            for topic in topics:
                topic_list.append(topic)
    except AttributeError as e:
        print("异常结束")
        return
    if topic_list:
        for topic in topic_list:
            yield from xm_parse(topic,title_list)


def main():
    x_flie=r"Test.xmind"
    out_file=r"xmind转换后.xlsx"
    temp=[]
    max_cols=0
    json_data= xmind_to_dict(x_flie)
    #提取数据,并找出最大深度(列数)
    for i,j in xm_parse(json_data[0]['topic']):
        temp.append(j)
        max_cols= max_cols if max_cols > len(j) else len(j)
    #对缺失数据采用补全
    for i in range(len(temp)):
        temp[i] = temp[i] + (max_cols - len(temp[i])) * [None]
    result=pd.DataFrame.from_records(temp,columns=["标题-{}".format(i+1) for i in range(max_cols)])
    result.to_excel(out_file,index=False,encoding='utf-8-sig')
    
if __name__ == '__main__':
    main()
  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
可以使用 `xmind` 和 `pandas` 库来将 xmind 换为 excel。 首先需要安装这两个库: ```python pip install xmind pandas ``` 然后使用以下代码可以将 xmind 换为 excel: ```python import pandas as pd from xmind.core import XMindDocument from xmind.core.topic import TopicElement def get_children(topics): """ 递归获取所有子话题 """ children = [] for topic in topics: children.append(topic) if topic.getSubTopics(): children.extend(get_children(topic.getSubTopics())) return children def xmind_to_excel(xmind_path, sheet_name='Sheet1'): # 读取 xmind 文件 xmind = XMindDocument.open(xmind_path) sheet_data = [] # 获取根话题 root_topic = xmind.getPrimarySheet().getRootTopic() # 获取所有子话题 topics = get_children([root_topic]) for topic in topics: # 获取话题文本 title = topic.getTitle() # 获取话题备注 notes = topic.getNotes() if notes: notes = notes.getContent() else: notes = '' # 获取话题标签 labels = ','.join([label.getName() for label in topic.getLabels()]) # 获取话题链接 links = ','.join([link.getTitle() for link in topic.getHyperlinks()]) # 获取话题优先级 priority = topic.getAttribute('priority') # 获取话题进度 progress = topic.getAttribute('progress') # 获取话题完成日期 due_date = topic.getAttribute('due-date') # 获取话题开始日期 start_date = topic.getAttribute('start-date') # 将话题数据添加进列表 sheet_data.append([title, notes, labels, links, priority, progress, due_date, start_date]) # 将数据换为 DataFrame df = pd.DataFrame(sheet_data, columns=['Title', 'Notes', 'Labels', 'Links', 'Priority', 'Progress', 'Due Date', 'Start Date']) # 写入 Excel 文件 df.to_excel('output.xlsx', sheet_name=sheet_name, index=False) ``` 使用方法: ```python xmind_to_excel('input.xmind', 'Sheet1') ``` 将会生成一个名为 `output.xlsx` 的 excel 文件。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

theskylife

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值