Excel中的表结构生成建表SQL

该文章介绍了如何使用Java将Excel文件中的表结构转换为MySQL的DDL(数据定义语言)语句,包括表名、字段名、类型、主键、自增等信息。
摘要由CSDN通过智能技术生成


import java.io.*;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author 彦
 * @since 2023/10/24 09:32
 * 将excel表结构转换为建表sql (MySql版本,其他版本自行用Chat GPT或其他工具转换)
 * excel格式样例
 * 表英文名 xxx
 * 表中文名 xxx
 * 字段名 类型 长度,小数点 是否为主键 是否自增	注释	是否非空
 *  xx varchar    255      Y       N     xx    Y
 *
 *  如果要生成txt文件,则打开175行注释
 */
@SuppressWarnings("CallToPrintStackTrace")
public class Excel2Sql {

    /**
     * 读取excel文件内容生成数据库表ddl
     *
     * @param filePath
     *            excel文件的绝对路径
     */
    public static void getDataFromExcel(String filePath) {
        if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
            System.err.println("文件不是excel类型");
        }
        InputStream fis = null;
        Workbook wookbook = null;
        try {
            fis = new FileInputStream(filePath);
            if (filePath.endsWith(".xls")) {
                try {
                    // 2003版本的excel,用.xls结尾
                    wookbook = new XSSFWorkbook(fis);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (filePath.endsWith(".xlsx")) {
                try {
                    // 2007版本的excel,用.xlsx结尾
                    wookbook = new XSSFWorkbook(fis);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Iterator<Sheet> sheets = null;
            if (wookbook != null) {
                sheets = wookbook.sheetIterator();
            }
            if (sheets != null) {
                while (sheets.hasNext()) {
                    StringBuilder ddl = new StringBuilder();
                    // 是否自增
                    boolean autoIncrement = false;
                    Sheet sheet = sheets.next();
                    System.err.println(
                        "--------------------------当前读取的sheet页:" + sheet.getSheetName() + "--------------------------");
                    // 当前读取行的行号
                    int rowId = 1;
                    Iterator<Row> rows = sheet.rowIterator();
                    String tableEnglishName;
                    String tableChineseName = "";
                    while (rows.hasNext()) {
                        Row row = rows.next();
                        // 获取表英文名
                        if (rowId == 1) {
                            Cell cell1 = row.getCell(0);
                            if (!"表英文名".equals(cell1.getStringCellValue())) {
                                System.err.println("第一行第一格应该为“表英文名”!");
                                return;
                            }
                            Cell cell2 = row.getCell(1);
                            tableEnglishName = cell2.getStringCellValue();
                            ddl.append("CREATE TABLE " + "`").append(tableEnglishName).append("` (").append("\r\n");
                            rowId++;
                            continue;
                        }

                        // 获取表中文名
                        if (rowId == 2) {
                            Cell cell1 = row.getCell(0);
                            if (!"表中文名".equals(cell1.getStringCellValue())) {
                                System.err.println("第2行第一格应该为“表中文名”!");
                                return;
                            }
                            Cell cell2 = row.getCell(1);
                            tableChineseName = cell2.getStringCellValue();
                            rowId++;
                            continue;
                        }

                        // 校验属性列名称和顺序
                        if (rowId == 3) {
                            if (row.getPhysicalNumberOfCells() != 7) {
                                System.err.println("第2行应该只有7个单元格!");
                                return;
                            }
                            Iterator<Cell> cells = row.cellIterator();
                            StringBuilder tableField = new StringBuilder();
                            while (cells.hasNext()) {
                                tableField.append(cells.next().getStringCellValue().trim());
                            }
                            if (!"字段名类型长度,小数点是否为主键是否自增注释是否非空".contentEquals(tableField)) {
                                System.err.println("第3行应该为 字段名 类型 长度,小数点 是否为主键 是否自增 注释 是否非空 !");
                                return;
                            }
                            rowId++;
                            continue;
                        }
                        if (!row.cellIterator().hasNext()) {
                            break;
                        }

                        // 字段名
                        String fieldName = row.getCell(0).getStringCellValue();
                        if (fieldName == null | "".equals(fieldName)) {
                            break;
                        }

                        // 字段类型
                        String fieldType = row.getCell(1).getStringCellValue();

                        // 字段长度
                        Cell cell3 = row.getCell(2);
                        cell3.setCellType(CellType.STRING);
                        String fieldLength = cell3.getStringCellValue();

                        // 是否为主键
                        Cell cell4 = row.getCell(3);

                        // 是否自增
                        Cell cell5 = row.getCell(4);

                        // 字段注释
                        String fieldComment = row.getCell(5).getStringCellValue();

                        // 是否非空 Y为是 N为不是
                        Cell cell6 = row.getCell(6);

                        ddl.append("`").append(fieldName).append("` ").append(fieldType)
                            .append(!"0".equals(fieldLength) ? "(" + fieldLength + ")" : "")
                            .append(cell4 != null && "Y".equals(cell4.getStringCellValue()) ? " PRIMARY KEY " : "")
                            .append(cell5 != null && "Y".equals(cell5.getStringCellValue()) ? " AUTO_INCREMENT " : "")
                            .append(" COMMENT '").append(fieldComment).append("'")
                            .append(cell6 != null && "Y".equals(cell6.getStringCellValue()) ? " NOT NULL" : " NULL")
                            .append(rows.hasNext() ? ",\r\n" : "\r\n");

                        // 设置是否自增
                        if (cell5 != null && "Y".equals(cell5.getStringCellValue())) {
                            autoIncrement = true;
                        }
                        rowId++;
                    }

                    if (ddl.toString().endsWith(",\r\n")) {
                        ddl.deleteCharAt(ddl.length() - 3);
                        ddl.append("\r\n");
                    }

                    ddl.append(") ENGINE=InnoDB ").append(autoIncrement ? "AUTO_INCREMENT=1" : "")
                        .append(" DEFAULT CHARSET=utf8 ")
                        .append(!"".equals(tableChineseName) ? "COMMENT = '" + tableChineseName + "'" : "").append(";\r\n");
                    ddl.append("-- --------------------------------------------------------------------------------\r\n");
                    System.err.println(ddl);
                    // 如果要生成txt文件,则打开此行注释
                    // writeMessageToFile(ddl.toString());
                }
            }
            System.err.println("转换结束");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static void writeMessageToFile(String message) {
        try {
            File file = new File("ddl.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file.getName(), true);
            fileWriter.write(message);
            fileWriter.close();

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

自行创建main运行

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值