java将mysql表结构写入到word表格中

文章目录

需要的依赖

xml 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<!--07版本的,行数不受限制-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

相关代码

java 复制代码
@Slf4j
public class ConstructionToWord {
    private final String DRIVER = "com.mysql.cj.jdbc.Driver";
    //private final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private final String URL = "jdbc:mysql://localhost:3306/数据库名称"
            +"?useUnicode=true&characterEncoding=utf8&useSSL=false";
    private final String USER_NAME = "";
    private final String PASS_WORD = "";
    private final String database = "数据库名称";
    private final String reportPath = "word文档生成路径";

    // 启动方法
    public static void main(String[] args) {

        try {
            ConstructionToWord rd = new ConstructionToWord();
            rd.report();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    // 获取查询数据
    public Map<String, List<TableColumn>> getData() throws Exception{

        System.out.println("数据生成中,请稍等...");
        Map<String,List<TableColumn>> map = new HashMap<String,List<TableColumn>>();

        List<Table> tables = getTables(database);

        for (Table table : tables) {
            List<TableColumn> columns = getColumns(database,table.getTableName());
            map.put(table.getTableName(),columns);
        }

        return map;

    }


    // 获取表字段信息
    public List<TableColumn>  getColumns(String database,String tableName) throws Exception{

        String sql = "select column_name,data_type, character_maximum_length,is_nullable,column_comment from information_schema.columns  where  table_schema=? and table_name=?";
        ResultSet rs = getConn(database,tableName,sql);

        List<TableColumn> tableColumns = new ArrayList<TableColumn>();

        while (rs.next()){

            TableColumn tc = new TableColumn();
            tc.setTableName(tableName);
            tc.setColumnName(rs.getString("column_name"));
            tc.setColumnType(rs.getString("data_type"));
            tc.setColumnSize(rs.getString("character_maximum_length"));
            tc.setIsNullable(rs.getString("is_nullable"));
            tc.setColumnComment(rs.getString("column_comment"));
            tableColumns.add(tc);

        }

        releaseConn();

        return tableColumns;

    }


    // 获取所有表
    public List<Table> getTables(String database) throws Exception{

        String  sql = "select table_name,table_comment from information_schema.tables where table_schema=?";
        ResultSet rs = getConn(database, "",sql);

        List<Table> tables = new ArrayList<Table>();
        while(rs.next()){
            Table table = new Table();
            table.setTableName(rs.getString( "table_name"));
            table.setTableCommont(rs.getString("table_comment"));
            tables.add(table);
        }

        releaseConn();
        return  tables;

    }

    // 连接数据库
    private ResultSet getConn(String dataBase,String tableName,String sql){

        try{
            log.info("1231qweqwe {}", sql);
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL,USER_NAME,PASS_WORD);
            pst = conn.prepareStatement(sql);
            pst.setString(1,dataBase);
            if(!"".equals(tableName)){
                pst.setString(2,tableName);
            }
            rs = pst.executeQuery();
            return  rs;

        }catch (Exception e){
            e.printStackTrace();
        }

        return null;

    }

    // 释放连接
    private void  releaseConn(){
        try{
            if(rs != null ){
                rs.close();
            }
            if(pst != null){
                pst.close();
            }
            if(conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    // 导出数据
    public void report()  throws  Exception{

        Map<String, List<TableColumn>> data = this.getData();       // 表名:表体
        List<Table> tables = this.getTables(this.database);         // 表体(列名、类型、注释)
        Map<String,String> tableMap = new HashMap<String,String>();              // 表名:中文名

        JSONObject json = new JSONObject((HashMap)data);

        for (Table table : tables) {
            tableMap.put(table.getTableName(),table.getTableCommont());
        }

        // 构建表格数据
        XWPFDocument document = new XWPFDocument();

        Integer i = 1;
        for (String tableName : data.keySet()) {

            XWPFParagraph paragraph = document.createParagraph();                // 创建标题对象
            XWPFRun run = paragraph.createRun();                                 // 创建文本对象
            run.setText((i+"、"+tableName+"    "+tableMap.get(tableName)));      // 标题名称
            run.setFontSize(14);                                                 // 字体大小
            run.setBold(true);                                                   // 字体加粗

            int j = 0;
            XWPFTable table = document.createTable(data.get(tableName).size()+1,5);
            // 第一行
            table.setCellMargins(10,50,10,200);
            table.getRow(j).getCell(0).setText("字段名称");
            table.getRow(j).getCell(1).setText("字段类型");
            table.getRow(j).getCell(2).setText("字段长度");
            table.getRow(j).getCell(3).setText("为空");
            table.getRow(j).getCell(4).setText("字段含义");
            j++;

            for (TableColumn tableColumn : data.get(tableName)) {

                table.getRow(j).getCell(0).setText(tableColumn.getColumnName());
                table.getRow(j).getCell(1).setText(tableColumn.getColumnType());
                table.getRow(j).getCell(2).setText(tableColumn.getColumnSize());
                table.getRow(j).getCell(3).setText(tableColumn.getIsNullable());
                table.getRow(j).getCell(4).setText(tableColumn.getColumnComment());
                j++;

            }
            i++;
        }

        // 文档输出
        FileOutputStream out = new FileOutputStream(reportPath + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString()+"_"+database +".docx");
        document.write(out);
        out.close();
        System.out.println("Word生成完成!!!");

    }

    // 表
    class Table{

        private String tableName;

        private String tableCommont;

        public String getTableName() {
            return tableName;
        }

        public void setTableName(String tableName) {
            this.tableName = tableName;
        }

        public String getTableCommont() {
            return tableCommont;
        }

        public void setTableCommont(String tableCommont) {
            this.tableCommont = tableCommont;
        }

    }

    // 表列信息
    class TableColumn{
        // 表名
        private String tableName;
        // 字段名
        private String columnName;
        // 字段类型
        private String columnType;
        // 字段长度
        private String columnSize;
        // 字段注释
        private String columnComment;
        // 可否为空
        private String isNullable;
        // 约束
        private String columnKey;

        public String getColumnSize() {
            return columnSize;
        }

        public void setColumnSize(String columnSize) {
            this.columnSize = columnSize;
        }

        public String getTableName() {
            return tableName;
        }

        public void setTableName(String tableName) {
            this.tableName = tableName;
        }

        public String getColumnName() {
            return columnName;
        }

        public void setColumnName(String columnName) {
            this.columnName = columnName;
        }

        public String getColumnType() {
            return columnType;
        }

        public void setColumnType(String columnType) {
            this.columnType = columnType;
        }

        public String getColumnComment() {
            return columnComment;
        }

        public void setColumnComment(String columnComment) {
            this.columnComment = columnComment;
        }

        public String getIsNullable() {
            return isNullable;
        }

        public void setIsNullable(String isNullable) {
            this.isNullable = isNullable;
        }

        public String getColumnKey() {
            return columnKey;
        }

        public void setColumnKey(String columnKey) {
            this.columnKey = columnKey;
        }

    }
}

可以通过SELECT * FROM information_schema.columns WHERE table_schema= '数据库名' AND TABLE_NAME= '表名';查看指定库下表的结构,可以查询哪些指标

相关推荐
Daniel 大东35 分钟前
BugJson因为json格式问题OOM怎么办
java·安全
Theodore_10225 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸6 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象6 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了7 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·7 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic7 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王7 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
i道i7 小时前
MySQL win安装 和 pymysql使用示例
数据库·mysql
武子康7 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud