增加了知识图谱导出excel

This commit is contained in:
chentianrui
2025-08-18 15:14:37 +08:00
parent ce2986fbe2
commit 3fd0b2af0c
610 changed files with 6062 additions and 4932473 deletions
+83 -12
View File
@@ -472,19 +472,90 @@ def get_node_cost_info(node_id):
@app.route("/api/export/<int:node_id>")
def export_node_tree(node_id):
"""导出整个工程知识图谱为Excel"""
"""导出整个工程知识图谱为Excel,每个一级子节点为一个工作表"""
try:
# 忽略传入的node_id参数,总是导出整个工程
excel_file, filename = KnowledgeGraphService.export_tree_to_excel(None)
if excel_file:
return send_file(
excel_file,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True,
download_name=f"{filename}.xlsx",
)
else:
return jsonify({"error": "无法生成Excel文件"}), 500
# 获取EngineeringData根节点
eng_data = KnowledgeGraphService.get_engineering_data_node()
if not eng_data:
return jsonify({"error": "未找到工程根节点"}), 404
root_id = eng_data["id"]
root_name = eng_data["name"]
# 获取根节点的一级子节点
children = KnowledgeGraphService.get_children_details(root_id)
# 创建Excel文件
output = BytesIO()
with pd.ExcelWriter(output, engine="openpyxl") as writer:
# 为每个一级子节点创建一个工作表
for child in children:
# 跳过费用相关节点
if child.get("labels") and any("Cost" in label for label in child.get("labels")):
continue
# 获取该子节点的完整树结构
tree_data = KnowledgeGraphService.get_full_tree_structure(child["id"])
if not tree_data:
continue
# 将树结构转换为扁平结构
flat_data = KnowledgeGraphService.flatten_tree_structure(tree_data)
# 创建DataFrame并写入工作表
df = pd.DataFrame(flat_data)
sheet_name = child.get("properties", {}).get("name", f"Sheet{len(writer.sheets) + 1}")
# 工作表名称不能超过31个字符且不能包含特殊字符
sheet_name = (
sheet_name[:31]
.replace(":", "")
.replace("\\", "")
.replace("/", "")
.replace("?", "")
.replace("*", "")
.replace("[", "")
.replace("]", "")
)
df.to_excel(writer, sheet_name=sheet_name, index=False)
# 添加一个总览工作表
overview_tree = KnowledgeGraphService.get_full_tree_structure(root_id)
overview_data = KnowledgeGraphService.flatten_tree_structure(overview_tree)
overview_df = pd.DataFrame(overview_data)
overview_df.to_excel(writer, sheet_name="总览", index=False)
output.seek(0)
return send_file(
output,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True,
download_name=f"{root_name}.xlsx",
)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/export_root")
def export_root_tree():
"""获取根节点并导出为Excel"""
try:
# 获取根节点
eng_data = KnowledgeGraphService.get_engineering_data_node()
if not eng_data:
return jsonify({"error": "未找到工程根节点"}), 404
# 导出Excel
output, root_name = KnowledgeGraphService.export_tree_to_excel()
if not output:
return jsonify({"error": root_name}), 500
# 返回Excel文件
return send_file(
output,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True,
download_name=f"{root_name}.xlsx",
)
except Exception as e:
return jsonify({"error": str(e)}), 500