快速使用Graphviz实现简单的图论绘制【java辅助文件读取】

84 阅读2分钟

软件安装

下载链接

点击进入下载

安装

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

使用教程

1、准备一个txt文件,然后转.dot格式

  txt文件内容:

   文件解释:
   定义节点的形状、颜色、字体:node[shape=circle,color=black,fontcolor=black,fontsize=25];  
   定义起点: 1[color= black,fontcolor=black,fontsize=25];
   定义关系: 1->2;(->是有向图)
digraph binaryTree{
    node[shape=circle,color=black,fontcolor=black,fontsize=25];
    1[color= black,fontcolor=black,fontsize=25];
    1->2;
    2->3;
    3->4;
    4->5;
    5->6;
	4->7;
	5->7;
	4->8;
	6->8;
	8->9;
	7->10;
	8->10;
	9->11;
	10->11;
	10->12;
	12->13;
	13->14;
	14->15;
	12->16;
	14->16;
	13->17;
	14->17;
	16->18;
	18->19;
	16->20;
	20->21;
	18->22;
	20->22;
	14->23;
	16->24;
	23->25;
	21->26;
	23->26;
	22->27;
	27->28;
	24->29;
	25->30;
	29->31;
	29->32;
	31->33;
	33->34;
	34->35;
	32->36;
}

在这里插入图片描述

文件转dot格式

2、根据excel快速生成关系

  如下表所示,A列数据为后置节点,B列数据为前置节点

节点关系表
//java代码 读取excel并生成关系文件
package mpcHomework;

//需要引入poi相关的包
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Main {

    public static void main(String[] args) throws Exception {
        File file = new File("E:\\Development\\Paint\\Graphviz\\files\\MPCExperience\\data1.txt");

        String str="";

        FileInputStream fileInputStream = new FileInputStream("E:\\Development\\Paint\\Graphviz\\files\\MPCExperience\\数据表.xlsx");
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);

        for (int i = 0; i < sheet.getLastRowNum()+1; i++) {
            Cell cell1 = sheet.getRow(i).getCell(0);
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String str1 = cell1.getStringCellValue();

            Cell cell2 = sheet.getRow(i).getCell(1);
            cell2.setCellType(Cell.CELL_TYPE_STRING);
            String str2 = cell2.getStringCellValue();

            if (str2.contains("、")){
                String[] split = str2.split("、");
                for (String s : split) {
                    str+=s+"->"+str1+";\n";
                }
            }else {
                str+=str2+"->"+str1+";\n";
            }
        }

        write(file, str, "GBK");

    }

    public static void write(File f, String text, String charset) throws Exception {
        FileOutputStream fstream = new FileOutputStream(f);
        try {
            fstream.write(text.getBytes(charset));
        } finally {
            fstream.close();
        }
    }

}

3、准备bat文件

  同样是先准备txt文件,然后转换格式为.bat,文件内容如下:   tree.png:定义输出的图片名字   tree.dot:定义要读取的dot文件

dot -Tpng -o tree.png tree.dot

在这里插入图片描述

批处理文件 双击即可生成图片

4、效果展示

在这里插入图片描述