使用 Python 将 XMind 转换为 Excel
Python 可以通过 xmindparser
和 openpyxl
库实现将 XMind 文件转换为 Excel 的功能。以下是具体实现方法:
安装依赖库
确保已安装以下库,若未安装,可通过 pip 安装:
pip install xmindparser openpyxl
解析 XMind 文件
使用 xmindparser
解析 XMind 文件内容:
import xmindparser
def parse_xmind(xmind_file):
content = xmindparser.parse(xmind_file)
return content
xmindparser
会将 XMind 文件解析为嵌套的字典结构,包含主题、子主题及备注等信息。
提取结构化数据
从解析结果中提取标题和子标题,整理为列表形式:
def extract_data(content):
data = []
for topic in content[0]['topic']['topics']:
main_title = topic['title']
for sub_topic in topic['topics']:
data.append([main_title, sub_topic['title']])
return data
此函数将主标题和子标题组合为二维列表,便于写入 Excel。
写入 Excel 文件
使用 openpyxl
将数据写入 Excel:
from openpyxl import Workbook
def write_to_excel(data, output_file):
wb = Workbook()
ws = wb.active
ws.append(["主标题", "子标题"]) # 表头
for row in data:
ws.append(row)
wb.save(output_file)
生成的 Excel 文件包含两列:主标题和子标题。
完整代码示例
整合以上步骤,实现完整功能:
import xmindparser
from openpyxl import Workbook
def xmind_to_excel(xmind_file, excel_file):
content = xmindparser.parse(xmind_file)
data = []
for topic in content[0]['topic']['topics']:
main_title = topic['title']
for sub_topic in topic['topics']:
data.append([main_title, sub_topic['title']])
wb = Workbook()
ws = wb.active
ws.append(["主标题", "子标题"])
for row in data:
ws.append(row)
wb.save(excel_file)
# 调用示例
xmind_to_excel("input.xmind", "output.xlsx")
扩展功能
-
处理多级嵌套
若 XMind 包含多级子主题,可通过递归提取数据:def extract_nested_data(topic, parent_title, data): current_title = f"{parent_title} > {topic['title']}" if parent_title else topic['title'] if 'topics' in topic: for sub_topic in topic['topics']: extract_nested_data(sub_topic, current_title, data) else: data.append([current_title])
-
添加样式
使用openpyxl.styles
为 Excel 添加边框、颜色等样式:from openpyxl.styles import Border, Side, Font border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) for row in ws.iter_rows(): for cell in row: cell.border = border
注意事项
- XMind 文件需为
.xmind
格式,旧版.xmind
可能需要转换。 - 复杂结构(如图标、关联线)可能无法直接转换,需手动调整。
- 若需批量处理,可通过
os.listdir()
遍历文件夹中的 XMind 文件。
通过以上方法,可以快速实现 XMind 到 Excel 的转换,便于进一步数据分析或共享。