(Java程序)Excel自动生成mysql表

读取excel生成字段

最近项目中遇到了一个费时间的事,就花了点时间写了一个小程序来做这件事。

description:现在在项目的前期设计阶段,需要从excel的数据库表格字段生成数据库,开始是手动搬砖,但是碰到了一个按照时间自增生成的列,一个表需要生成几百列的字段,手敲感觉要命,就写了以下的小程序来完成数据库表的生成和字段的自动生成。如下图,有字段是要分段生成的。

(Java程序)Excel自动生成mysql表_第1张图片

以下程序生成的数据库表名就是excel的sheet的名字,类型默认是bigint(20),varchar(200),double(3,8),datatime。

package service;


import bean.Excel;
import bean.Table;
import jxl.Sheet;
import jxl.Workbook;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :yangqingbo
 * @date :Created in 2019/9/25 15:57
 * @description:excel自动生成mysql表结构
 *      path:excel表格的路径,注意此程序只能使用.xls的表格
 *      url: mysql的连接信息
 *      username:mysql的用户名
 *      password:mysql的密码
 *      drivernaem:对应pom中的mysql版本,(5.x和8.x的版本驱动不同,我这里是8.x的,5.x的驱动com.mysql.jdbc.Driver)
 * 本程序需要使用到的依赖:net.sourceforge.jexcelapi.jxl.2.6.12;和对应mysql驱动版本的mysql架包;jdk8
 */
public class ExcelTest {

    static String path = "F:\\Excel\\hah.xls";
    static String url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    static String userName = "root";
    static String password = "123456";
    static String driverName = "com.mysql.cj.jdbc.Driver";

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        createTable(path, url, userName, password, driverName);
    }

    /**
     * @param path       excel本地路径
     * @param url        数据库连接地址
     * @param userName   用户名
     * @param password   密码
     * @param driverName 驱动
     * @throws Exception
     */
    public static void createTable(String path, String url, String userName, String password, String driverName) throws Exception {
        List tableList = getExcelContent(path);
        //遍历所有表
        for (Table table : tableList) {

            List excelContent = table.getParamList();
            Connection conn = getMySQLConnection(url, userName, password, driverName);
            Statement statement = conn.createStatement();
            StringBuilder sb = new StringBuilder();
            sb.append("CREATE TABLE `" + table.getTableName() + "` (\n");
            //遍历表的字段
            for (int k = 0; k < excelContent.size(); k++) {
                Excel excel = excelContent.get(k);
                //判断是否有需要自动生成的字段。
                // 如果有,先将第一个0000的添加进字段,然后按照步长,每次都添加一个进去,注意要修改注释
                if (excel.getName().contains("00")) {
                    addString(sb, excel);
                    //算出步长
                    String begin = excel.getName().substring(excel.getName().length() - 2);
                    Excel next = excelContent.get(k + 1);
                    String nextBegin = next.getName().substring(next.getName().length() - 2);
                    int step = Integer.parseInt(nextBegin) - Integer.parseInt(begin);     //步长
                    // System.out.println("begin:" + begin + "\nafter" + nextBegin + "\nstep" + step);
                    //生成n个字段
                    generatorString(sb, excel, step);
                    k = k + 3;
                    continue;
                }
                //添加表字段
                addString(sb, excel);
            }
            sb.append("PRIMARY KEY (`" + excelContent.get(0).getName() + "`)\n) ");
            sb.append("ENGINE = InnoDB\n" +
                    "DEFAULT CHARACTER SET = utf8\n" +
                    "COLLATE = utf8_general_ci\n");
            sb.append("COMMENT = '" + table.getTableComment() + "'\n" +
                    "ROW_FORMAT = COMPACT;");
            System.out.println(sb);
            // statement.executeUpdate(sb.toString());
            statement.close();
        }
    }

    /**
     * 拼接表字段信息进sql语句
     *
     * @param sb    拼接的sql语句的stringBuilder
     * @param excel 表字段类
     */
    public static void addString(StringBuilder sb, Excel excel) {
        sb.append("`" + excel.getName() + "` " + excel.getType() + " " + excel.getNullable());
        if (excel.getDefaultValue().length() != 0) {
            sb.append(" DEFAULT " + excel.getDefaultValue());
        }
        sb.append(" COMMENT '" + excel.getComment() + "',\n");
    }

    /**
     * 生成自增字段,0000-2345类似的这种字段
     *
     * @param sb    拼接的sql语句的stringBuilder
     * @param excel 表字段类模板
     * @param step  自增生成的字段步长
     */
    public static void generatorString(StringBuilder sb, Excel excel, int step) {
        LocalTime begintime = LocalTime.of(0, 0);
        //生成n个字段
        for (LocalTime time = begintime.plusMinutes(step); !time.toString().equals(begintime.toString()); time = time.plusMinutes(step)) {
            Excel nextParam = new Excel();
            //除了字段名和注释其他复制第一个0000的字段
            nextParam.setType(excel.getType());
            nextParam.setNullable(excel.getNullable());
            nextParam.setDefaultValue(excel.getDefaultValue());
            //获取字段名称共同前缀,将后缀修改掉
            String namePrefix = excel.getName().substring(0, excel.getName().length() - 4);
            String nameSuffix = time.toString().replace(":", "");
            // System.out.println("nameSuffix" + nameSuffix);
            nextParam.setName(namePrefix + nameSuffix);

            //获取字段注释共同后缀
            String commentSuffix = excel.getComment().substring(5);
            nextParam.setComment(time.toString() + commentSuffix);
            addString(sb, nextParam);
            // System.out.println(nextParam);
        }
    }

    /**
     * 获取数据库连接
     *
     * @param url        数据库连接
     * @param username   用户名
     * @param password   密码
     * @param driverName 驱动
     * @return
     */
    public static Connection getMySQLConnection(String url, String username, String password, String driverName) {
        Connection conn = null;
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 读取excel生成表对象集合
     *
     * @param path 本地excel表格
     * @return 表信息集合
     * @throws Exception
     */
    public static List
getExcelContent(String path) throws Exception { List
tableList = new ArrayList<>(); File file = new File(path); Workbook workbook = Workbook.getWorkbook(file); Sheet[] sheets = workbook.getSheets(); // System.out.println("一共有" + sheets.length + "个sheet"); for (Sheet shell : sheets) { Table table = new Table(); table.setTableName(shell.getName()); table.setTableComment(shell.getName()); List excels = new ArrayList<>(); int rows = shell.getRows(); int clomns = shell.getColumns(); for (int i = 0; i < rows; i++) { if (i == 0) { continue; } Excel excel = new Excel(); for (int j = 0; j < clomns; j++) { switch (j) { case 0: excel.setName(shell.getCell(j, i).getContents().trim()); break; case 1: switch (shell.getCell(j, i).getContents().trim()) { case "int": excel.setType("bigint(20)"); break; case "varchar": excel.setType("varchar(200)"); break; case "double": excel.setType("double(8,3)"); break; case "datetime": excel.setType("datetime"); break; default: excel.setType(shell.getCell(j, i).getContents().trim()); } break; case 2: excel.setDefaultValue(shell.getCell(j, i).getContents().trim()); break; case 3: if ("是".equals(shell.getCell(j, i).getContents().trim())) { excel.setNullable("NOT NULL"); } else { excel.setNullable(""); } break; case 4: break; case 5: excel.setComment(shell.getCell(j, i).getContents().trim()); break; default: break; } } excels.add(excel); table.setParamList(excels); } tableList.add(table); } return tableList; } }

 

你可能感兴趣的:(Java,Excel,PIO)