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

文章目录

  • 需要的依赖

需要的依赖

<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>

相关代码

@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= '表名';查看指定库下表的结构,可以查询哪些指标

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/885900.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

DBC差异比较工具DBCCompare_原理介绍(四)

DBC比对工具UI图片 DBC比对工具&#xff1a;功能详解与源码分析 在现代汽车开发和诊断过程中&#xff0c;DBC&#xff08;Database Container&#xff09;文件扮演着至关重要的角色。它们详细描述了CAN&#xff08;Controller Area Network&#xff09;网络中各消息和信号的详…

GB28181信令交互流程及Android端设备对接探讨

GB28181规范必要性 好多开发者在做比如执法记录仪、智能安全帽、智能监控等设备端视频回传技术方案选型的时候&#xff0c;不清楚到底是用RTSP、RTMP还是GB28181&#xff0c;对GB28181相对比较陌生&#xff0c;我们就GB28181规范的必要性&#xff0c;做个探讨&#xff1a; 实现…

【北京迅为】《STM32MP157开发板嵌入式开发指南》- 第十八章 Linux编写第一个自己的命令

iTOP-STM32MP157开发板采用ST推出的双核cortex-A7单核cortex-M4异构处理器&#xff0c;既可用Linux、又可以用于STM32单片机开发。开发板采用核心板底板结构&#xff0c;主频650M、1G内存、8G存储&#xff0c;核心板采用工业级板对板连接器&#xff0c;高可靠&#xff0c;牢固耐…

企业安全策略制定

如今&#xff0c;网络安全是所有组织的必需品&#xff0c;而不是奢侈品。现代企业面临着针对其数据、网络和系统的复杂且不断演变的威胁。 即使一个漏洞也可能导致严重违规、财务损失和声誉受损。正如堡垒依靠多层防御共同作用一样&#xff0c;公司的安全措施必须作为一个整体…

【学习笔记】手写 Tomcat 六

目录 一、线程池 1. 构建线程池的类 2. 创建任务 3. 执行任务 测试 二、URL编码 解决方案 测试 三、如何接收客户端发送的全部信息 解决方案 测试 四、作业 1. 了解工厂模式 2. 了解反射技术 一、线程池 昨天使用了数据库连接池&#xff0c;我们了解了连接池的优…

渗透测试--文件上传常用绕过方式

文件上传常用绕过方式 1.前端代码&#xff0c;限制只允许上传图片。修改png为php即可绕过前端校验。 2.后端校验Content-Type 校验文件格式 前端修改&#xff0c;抓取上传数据包&#xff0c;并且修改 Content-Type 3.服务端检测&#xff08;目录路径检测&#xff09; 对目…

医院体检管理系统小程序的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;用户管理&#xff0c;体检分类管理&#xff0c;体检套餐管理&#xff0c;体检预约管理&#xff0c;体检报告管理&#xff0c;系统管理 微信端账号功能包括&#xff1a;系统首页&#xff0c;体检套餐&a…

四、Drf认证组件

四、Drf认证组件 4.1 快速使用 from django.shortcuts import render,HttpResponse from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.authentication import BaseAuthentication from rest_framework.exception…

数据结构:将复杂的现实问题简化为计算机可以理解和处理的形式

整句话的总体意义是&#xff0c;**数据结构是用于将现实世界中的实体和关系抽象为数学模型&#xff0c;并在计算机中表示和实现的关键工具**。它不仅包括如何存储数据&#xff0c;还包括对这些数据的操作&#xff0c;能够有效支持计算机程序的运行。通过这一过程&#xff0c;数…

利用PDLP扩展线性规划求解能力

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

Java项目实战II基于Java+Spring Boot+MySQL的甘肃非物质文化网站设计与实现(源码+数据库+文档)

目录 一、前言 二、技术介绍 三、系统实现 四、文档参考 五、核心代码 六、源码获取 全栈码农以及毕业设计实战开发&#xff0c;CSDN平台Java领域新星创作者 一、前言 甘肃省作为中国历史文化名省&#xff0c;拥有丰富的非物质文化遗产资源&#xff0c;涵盖表演艺术、手…

TypeScript 封装 Axios 1.7.7

随着Axios版本的不同&#xff0c;类型也在改变&#xff0c;以后怎么写类型&#xff1f; 1. 封装Axios 将Axios封装成一个类&#xff0c;同时重新封装request方法 重新封装request有几个好处&#xff1a; 所有的请求将从我们定义的requet请求中发送&#xff0c;这样以后更换…

Golang | Leetcode Golang题解之第441题排列硬币

题目&#xff1a; 题解&#xff1a; func arrangeCoins(n int) int {return sort.Search(n, func(k int) bool { k; return k*(k1) > 2*n }) }

【Unity服务】如何使用Unity Version Control

Unity上的线上服务有很多&#xff0c;我们接触到的第一个一般就是Version Control&#xff0c;用于对项目资源的版本管理。 本文介绍如何为项目添加Version Control&#xff0c;并如何使用&#xff0c;以及如何将项目与Version Control断开链接。 其实如果仅仅是对项目资源进…

09_OpenCV彩色图片直方图

import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inlineimg cv2.imread(computer.jpeg, 1) img cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img) plt.show()plot绘制直方图 plt.hist(img.ravel(), 256) #ravel() 二维降一维 256灰度级…

学习记录:js算法(五十):二叉树的右视图

文章目录 二叉树的右视图我的思路网上思路 总结 二叉树的右视图 给定一个二叉树的 根节点 root&#xff0c;想象自己站在它的右侧&#xff0c;按照从顶部到底部的顺序&#xff0c;返回从右侧所能看到的节点值。 图一&#xff1a; 示例 1:如图一 输入: [1,2,3,null,5,null,4] …

C++面向对象基础

目录 一.函数 1.内联函数 2.函数重载 3.哑元函数 二.类和对象 2.1 类的定义 2.2 创建对象 三. 封装&#xff08;重点&#xff09; 四. 构造函数 constructor&#xff08;重点&#xff09; 4.1 基础使用 4.2 构造初始化列表 4.3 构造函数的调用方式&#xff08;掌握…

解决方法:PDF文件打开之后不能打印?

打开PDF文件之后&#xff0c;发现文件不能打印&#xff1f;这是什么原因&#xff1f;首先我们需要先查看一下自己的打印机是否能够正常运行&#xff0c;如果打印机是正常的&#xff0c;我们再查看一下&#xff0c;文件中的打印功能按钮是否是灰色的状态。 如果PDF中的大多数功…

秋招内推--招联金融2025

【投递方式】 直接扫下方二维码&#xff0c;或点击内推官网https://wecruit.hotjob.cn/SU61025e262f9d247b98e0a2c2/mc/position/campus&#xff0c;使用内推码 igcefb 投递&#xff09; 【招聘岗位】 后台开发 前端开发 数据开发 数据运营 算法开发 技术运维 软件测试 产品策…

数据结构-LRU缓存(C语言实现)

遇到困难&#xff0c;不必慌张&#xff0c;正是成长的时候&#xff0c;耐心一点&#xff01; 目录 前言一、题目介绍二、实现过程2.1 实现原理2.2 实现思路2.2.1 双向链表2.2.2 散列表 2.3 代码实现2.3.1 结构定义2.3.2 双向链表操作实现2.3.3 实现散列表的操作2.3.4 内存释放代…