将数据库查询结果快速生成markdown格式表格

在写数据库相关博文时,经常需要把结果集展示到页面上。用图片真的是太麻烦了,一篇文章都没写完我就已经忍无可忍了。
于是写了一段代码来生成基础的markdown格式表格代码。

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import connTest.conn.SqlmapFactory;
/**
 * 
 * @author nayi224
 *
 */
public class MarkDown {

    private static SqlMapClient client = null;
    private static String configFile = "config/SqlMapConfig.xml";
    private static Reader r = null;

    static {
        try {
            r = Resources.getResourceAsReader(configFile);
            client = SqlMapClientBuilder.buildSqlMapClient(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     * @throws SQLException 
     */
    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub
        List l2 = client.queryForList("blog.test");
        System.out.println("\r\r");
        prt(l2);
    }

    private static void prt(List list){
        if(list == null || list.size() == 0) return;
        LinkedHashMap temp = list.get(0);

        String str = "|";
        for(Object obj: temp.keySet()){
            str += obj + "|";
        }
        str += "\r|";
        for(Object obj: temp.keySet()){
            str += "----|";
        }

        for(LinkedHashMap tempMap: list){
            str += "\r|";
            for(Object obj: tempMap.keySet()){
                str += (tempMap.get(obj) == null ? "" : tempMap.get(obj)) + "|";
            }
        }

        System.out.println(str);
    }

}

生成数据例

|DEPT_ID|PARENT_ID|DEPT_NAME|DEPT_RANK|VAL|
|----|----|----|----|----|
|root||全国|/root|0|
|root_1|root|北京市|/root/root_1|2000|
|ln_root|root|辽宁省|/root/ln_root|200|
|ln_ys|ln_root|辽宁省沈阳市|/root/ln_root/ln_ys|1000|
|ln_sy_hp|ln_ys|辽宁省沈阳和平区|/root/ln_root/ln_ys/ln_sy_hp|500|
|ln_ys_dd|ln_ys|辽宁省沈阳大东区|/root/ln_root/ln_ys/ln_ys_dd|600|
|jl_root|root|吉林省|/root/jl_root|0|
|jl_jl|jl_root|吉林省吉林市|/root/jl_root/jl_jl|200|
|jl_cc|jl_root|吉林省长春市|/root/jl_root/jl_cc|500|

终于不怕强迫症复发,一张图截n遍了。

你可能感兴趣的:(markdown,懒人福利)