前言:
在實際項目中會遇到建主題數據庫的工作(主題數據庫定義:面向特定的學科和應用領域,由若干的邏輯相關的數據源按照統一的標准規范整合形成,具有系統性和完整性,並通過統一的系統提供一站式服務的數據庫。),就是批量按照需求建表,此時就需要一些代碼輔助操作。
思路:
1、相關人員會提供表結構文件,類似如下圖:

2、提取有用信息,單獨建立excle文件,如下圖:

3、使用代碼把信息讀取出來,
4、生成SQL語句,
具體實現:
1、准備java代碼需要依賴的jar包:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency>
2、測試用的實體類:
package com.test.word; import java.io.Serializable; /** * 模擬的實體類 * @author xieh * */ public class Test implements Serializable{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Test [id=" + id + ", name=" + name + "]"; } }
3、操作excle表工具類:
package com.test.word; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * excle工具類 * * @author xieh 2019/11/24 使用的jar包是:poi-4.1.0.jar 和 poi-ooxml-4.1.0.jar * */ public class ExcelUtil { /** * 讀取excle內容:注意此方法不兼容.xlsx文件 * @throws Exception */ @SuppressWarnings("resource") public static List<Map<String, String>> excelRead() throws Exception { //用流的方式先讀取到你想要的excel的文件 //FileInputStream fis=new FileInputStream(new File(System.getProperty("user.dir")+"/src/excel.xls")); FileInputStream fis = new FileInputStream(new File("D:/a.xls")); // 解析excel POIFSFileSystem pSystem = new POIFSFileSystem(fis); // 獲取整個excel HSSFWorkbook hb = new HSSFWorkbook(pSystem); System.out.println(hb.getNumCellStyles()); // 獲取第一個表單sheet HSSFSheet sheet = hb.getSheetAt(0); // 獲取第一行 int firstrow = sheet.getFirstRowNum(); // 獲取最后一行 int lastrow = sheet.getLastRowNum(); // 存取最后結果 List<Map<String, String>> result = new ArrayList<Map<String, String>>(); // 循環行數依次獲取列數 for (int i = firstrow; i < lastrow + 1; i++) { // 獲取哪一行i Row row = sheet.getRow(i); // 存放每行的鍵值對結果 Map<String, String> tempMap = new HashMap<String, String>(); if (row != null) { // 獲取這一行的第一列 int firstcell = row.getFirstCellNum(); // 獲取這一行的最后一列 int lastcell = row.getLastCellNum(); // 創建一個集合,用處將每一行的每一列數據都存入集合中 //List<String> list = new ArrayList<String>(); for (int j = firstcell; j < lastcell; j++) { // 獲取第j列 Cell cell = row.getCell(j); if (cell != null && !("").equals(cell.toString())) { //System.out.print(cell + "\t"); //list.add(cell.toString()); tempMap.put("c" + j, cell.toString().trim()); } } // 存放每行的結果 result.add(tempMap); }// row if end }// for end fis.close(); System.out.println(result.toString()); return result; } /** * 此方法兼容.xls 和 .xlsx格式,建議使用 * @param path excle文件路徑 * @param sheetIndex excle文件的Sheet頁的下標,從0開始 * @return excle表中的內容 * @throws Exception */ @SuppressWarnings("resource") public static List<Map<String, String>> excelXRead(String path,int sheetIndex) throws Exception { //用流的方式先讀取到你想要的excel的文件 //FileInputStream fis=new FileInputStream(new File(System.getProperty("user.dir")+"/src/excel.xls")); File excel = new File(path); String[] split = excel.getName().split("\\."); //.是特殊字符,需要轉義 Workbook wb = null; FileInputStream fis = null; //根據文件后綴(xls/xlsx)進行判斷 if ( "xls".equals(split[1])){ fis = new FileInputStream(excel); //文件流對象 wb = new HSSFWorkbook(fis); }else if ("xlsx".equals(split[1])){ wb = new XSSFWorkbook(excel); }else { System.out.println("文件類型錯誤!"); return new ArrayList<>(); } //開始解析 Sheet sheet = wb.getSheetAt(sheetIndex); //讀取sheet 0 // 獲取第一行 int firstrow = sheet.getFirstRowNum() + 1; //第一行是列名,所以不讀 // 獲取最后一行 int lastrow = sheet.getLastRowNum(); // 存取最后結果 List<Map<String, String>> result = new ArrayList<Map<String, String>>(); // 循環行數依次獲取列數 for (int i = firstrow; i < lastrow + 1; i++) { // 獲取哪一行i Row row = sheet.getRow(i); // 存放每行的鍵值對結果 Map<String, String> tempMap = new HashMap<String, String>(); if (row != null) { // 獲取這一行的第一列 int firstcell = row.getFirstCellNum(); // 獲取這一行的最后一列 int lastcell = row.getLastCellNum(); // 創建一個集合,用處將每一行的每一列數據都存入集合中 //List<String> list = new ArrayList<String>(); for (int j = firstcell; j < lastcell; j++) { // 獲取第j列 Cell cell = row.getCell(j); if (cell != null && !("").equals(cell.toString())) { //System.out.print(cell + "\t"); //list.add(cell.toString()); tempMap.put("c" + j, cell.toString().trim()); } } // 存放每行的結果 result.add(tempMap); }// row if end }// for end if(null != fis){ fis.close(); } System.out.println(result.toString()); return result; } /** * 創建和寫入excle內容 * @param exportList 實體類list * @param file 生成的文件路徑 * @throws Exception */ public static void writeXls(List<Test> exportList, File file) throws Exception { String[] options = { "ID", "內容", "名字" }; XSSFWorkbook book = new XSSFWorkbook(); CreationHelper createHelper = book.getCreationHelper(); XSSFCellStyle style = book.createCellStyle(); XSSFCellStyle dateStyle = book.createCellStyle(); XSSFDataFormat format = book.createDataFormat(); style.setWrapText(true); dateStyle.setWrapText(true); XSSFSheet sheet = book.createSheet("sheet"); sheet.setColumnWidth(3, 13000); sheet.setDefaultColumnWidth(20); XSSFRow firstRow = sheet.createRow(0); XSSFCell[] firstCells = new XSSFCell[3]; CellStyle styleBlue = book.createCellStyle(); // 樣式對象 // 設置單元格的背景顏色為淡藍色 styleBlue.setWrapText(true);// 指定當單元格內容顯示不下時自動換行 Font font = book.createFont(); //font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setFontHeight((short) 280); style.setFont(font); dateStyle.setFont(font); dateStyle.setDataFormat(format.getFormat("yyyy-mm-dd")); styleBlue.setFont(font); for (int j = 0; j < options.length; j++) { firstCells[j] = firstRow.createCell(j); firstCells[j].setCellStyle(styleBlue); firstCells[j].setCellValue(new XSSFRichTextString(options[j])); } getExport(sheet, style, createHelper, exportList, dateStyle); if (file.exists()) { file.delete(); } file.createNewFile(); OutputStream os = new FileOutputStream(file); book.write(os); os.close(); } /** * excle實體數據寫入 * @param sheet * @param style * @param createHelper * @param exportList * @param dateStyle */ private static void getExport(XSSFSheet sheet, XSSFCellStyle style, CreationHelper createHelper, List<Test> exportList, XSSFCellStyle dateStyle) { // 遍歷實例類的list集合 for (int i = 0; i < exportList.size(); i++) { // 創建行 XSSFRow row = sheet.createRow(i + 1); // 實體類 Test export = exportList.get(i); // 第一列 XSSFCell hotelId = row.createCell(0); hotelId.setCellStyle(style); // 第二列 XSSFCell hotelName = row.createCell(1); hotelName.setCellStyle(dateStyle); // 第三列 XSSFCell chargeCount = row.createCell(2); chargeCount.setCellStyle(style); // 設置值 hotelId.setCellValue(export.getId()); hotelName.setCellValue("測試"); chargeCount.setCellValue(export.getName()); // ta.append("寫入excel開始,行數是" + (i + 1) + "\n"); }// for end } /** * 測試 * * @param args */ public static void main(String[] args) { try { ExcelUtil.excelRead(); ExcelUtil.excelXRead("D:/柱子.xlsx",0); ExcelUtil.excelXRead("D:/a.xls",0); List<Test> show = new ArrayList<Test>(); Test test1 = new Test(); test1.setId(1); test1.setName("xieh"); Test test2 = new Test(); test2.setId(2); test2.setName("xieh"); show.add(test1); show.add(test2); ExcelUtil.writeXls(show, new File("D:/bbb.xls")); ExcelUtil.writeXls(show, new File("D:/aaa.xlsx")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4、生成SQL表結構的工具類:
package com.test.word; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 數據庫建表工具類 * @author xieh 2019/11/27 * */ public class SQLTableUtil { //private String mysql = "MYSQL"; //private String mssql = "MSSQL"; //private String oracle = "ORACLE"; //private String psql = "PSQL"; /** * MySQL數據庫創建表SQL語句生成 * @param listSqlFiled * @return */ public static String createMYSQL(List<Map<String, String>> listSqlFiled){ if(listSqlFiled != null && listSqlFiled.size()>0){ List<String> priKeyArray = new ArrayList<String>();// 主鍵集合 StringBuilder sqlStr = new StringBuilder(); // 獲取第一個map,存在表名 Map<String, String> mapFirst = listSqlFiled.get(0); /*int countMapFirst = 0;// 控制第一行的表名和表注釋遍歷次數 for(Map.Entry<String, String> entry:mapFirst.entrySet()){ if(countMapFirst == 0){ sqlStr.append("DROP TABLE IF EXISTS `"+ entry.getValue() +"`;\n"); sqlStr.append("CREATE TABLE `"+ entry.getValue() +"` (\n"); } }*/ sqlStr.append("DROP TABLE IF EXISTS `"+ mapFirst.get("c0") +"`;\n"); sqlStr.append("CREATE TABLE `"+ mapFirst.get("c0") +"` (\n"); int length = listSqlFiled.size(); // 遍歷list集合 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append("`"+ map.get("c1") +"`\t "+ map.get("c2") +"\t"); // 是否為主鍵並且主鍵不能為空 if(map.get("c3").equalsIgnoreCase("Y")){ priKeyArray.add(map.get("c1")); sqlStr.append("NOT NULL COMMENT '"+map.get("c5")+"',\n"); //表示結束了到最后一行了,並且只有一個主鍵 if(i >= length - 1 && priKeyArray.size() == 1){// 只有一個主鍵時 sqlStr.append("PRIMARY KEY (`"+ priKeyArray.get(0) +"`)\n"); sqlStr.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); // 表示到最后一行了,並且存在多個主鍵 }else if(i >= length - 1 && priKeyArray.size() > 1){// 多個主鍵時 sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append("`"+ priKeyArray.get(k) +"`) USING BTREE \n"); }else{ sqlStr.append("`"+ priKeyArray.get(k) +"`,"); } } sqlStr.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); } // 非主鍵,直接判斷是否允許為空 }else { // 表示沒有主鍵,並且到最后一個了 if(priKeyArray.size() <=0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append("DEFAULT NULL COMMENT '"+map.get("c5")+"'\n"); }else{ sqlStr.append("NOT NULL COMMENT '"+map.get("c5")+"'\n"); } sqlStr.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); // 表示有主鍵,並且是到最后一行了 }else if(priKeyArray.size() >0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append("DEFAULT NULL COMMENT '"+map.get("c5")+"',\n"); }else{ sqlStr.append("NOT NULL COMMENT '"+map.get("c5")+"',\n"); } // 表示只有一個主鍵 if(priKeyArray.size() == 1){ sqlStr.append("PRIMARY KEY (`"+ priKeyArray.get(0) +"`)\n"); sqlStr.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); // 表示有多個主鍵 }else{ sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append("`"+ priKeyArray.get(k) +"`) USING BTREE \n"); }else{ sqlStr.append("`"+ priKeyArray.get(k) +"`,"); } } sqlStr.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); } // 沒有到最后一行繼續追加 }else{ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append("DEFAULT NULL COMMENT '"+map.get("c5")+"',\n"); }else{ sqlStr.append("NOT NULL COMMENT '"+map.get("c5")+"',\n"); } } }// }// for end return sqlStr.toString(); }else{ return ""; } } /** * sqlserver數據庫創建表SQL語句 * @param listSqlFiled * @return */ public static String createMSSQL(List<Map<String, String>> listSqlFiled){ if(listSqlFiled != null && listSqlFiled.size()>0){ StringBuilder sqlStr = new StringBuilder(); // 獲取第一個map,存在表名 Map<String, String> mapFirst = listSqlFiled.get(0); sqlStr.append("IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].["+ mapFirst.get("c0") +"]') AND type IN ('U'))\n"); sqlStr.append("DROP TABLE [dbo].["+ mapFirst.get("c0") +"]\n"); sqlStr.append("GO\n"); sqlStr.append("CREATE TABLE "+ mapFirst.get("c0") +" (\n"); int length = listSqlFiled.size(); // 遍歷list集合:生成基本表結構階段 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append("["+ map.get("c1") +"]\t "+ map.get("c2") +"\t"); // 是否為主鍵並且主鍵不能為空 if(map.get("c3").equalsIgnoreCase("Y")){ if(i >= length - 1){// 表示最后一個並且是主鍵 sqlStr.append("primary key NOT NULL\n"); sqlStr.append(")"); }else{ sqlStr.append("primary key NOT NULL ,\n"); } // 非主鍵,直接判斷是否允許為空 }else { if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 if(i >= length -1){// 表示允許為空並且是最后一個 sqlStr.append("DEFAULT NULL\n"); sqlStr.append(")"); }else{// 表示允許為空繼續追加 sqlStr.append("DEFAULT NULL ,\n"); } }else{// 不允許為空 if(i >= length -1){// 表示不允許為空並且是最后一個 sqlStr.append("NOT NULL\n"); sqlStr.append(")"); }else{// 表示不允許為空繼續追加 sqlStr.append("NOT NULL ,\n"); } } }// }// for end基本表結構生成完成 // 開始追加注釋階段 sqlStr.append("\n"); for(int i = 1; i < length; i ++){ Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append("EXEC sp_addextendedproperty\n"); sqlStr.append("'MS_Description', N'"+ map.get("c5") +"',\n"); sqlStr.append("'SCHEMA', N'dbo',\n"); sqlStr.append("'TABLE', N'"+ mapFirst.get("c0") +"',\n"); sqlStr.append("'COLUMN', N'"+ map.get("c1") +"'\n"); sqlStr.append("GO\n"); sqlStr.append("\n"); } return sqlStr.toString(); }else{ return ""; } } /** * Oracle數據創建表SQL語句 * @param listSqlFiled * @param dbUserName * @return */ public static String createORACLE(List<Map<String, String>> listSqlFiled,String dbUserName){ if(listSqlFiled != null && listSqlFiled.size()>0){ List<String> priKeyArray = new ArrayList<String>();// 主鍵集合 StringBuilder sqlStr = new StringBuilder(); // 獲取第一個map,存在表名 Map<String, String> mapFirst = listSqlFiled.get(0); sqlStr.append("create table "+ dbUserName +"."+ mapFirst.get("c0") +"(\n"); int length = listSqlFiled.size(); // 遍歷list集合 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append(""+ map.get("c1") +"\t "+ map.get("c2") +"\t"); // 是否為主鍵並且主鍵不能為空 if(map.get("c3").equalsIgnoreCase("Y")){ priKeyArray.add(map.get("c1")); sqlStr.append("NOT NULL,\n"); //表示結束了到最后一行了,並且只有一個主鍵 if(i >= length - 1 && priKeyArray.size() == 1){// 只有一個主鍵時 sqlStr.append("PRIMARY KEY ("+ priKeyArray.get(0) +")\n"); sqlStr.append(");\n"); // 表示到最后一行了,並且存在多個主鍵 }else if(i >= length - 1 && priKeyArray.size() > 1){// 多個主鍵時 sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append(""+ priKeyArray.get(k) +")\n"); }else{ sqlStr.append(""+ priKeyArray.get(k) +","); } } sqlStr.append(");\n"); } // 非主鍵,直接判斷是否允許為空 }else { // 表示沒有主鍵,並且到最后一個了 if(priKeyArray.size() <=0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append("\n"); }else{ sqlStr.append("NOT NULL\n"); } sqlStr.append(");\n"); // 表示有主鍵,並且是到最后一行了 }else if(priKeyArray.size() >0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append(",\n"); }else{ sqlStr.append("NOT NULL,\n"); } // 表示只有一個主鍵 if(priKeyArray.size() == 1){ sqlStr.append("PRIMARY KEY ("+ priKeyArray.get(0) +")\n"); sqlStr.append(");\n"); // 表示有多個主鍵 }else{ sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append(""+ priKeyArray.get(k) +")\n"); }else{ sqlStr.append(""+ priKeyArray.get(k) +","); } } sqlStr.append(");\n"); } // 沒有到最后一行繼續追加 }else{ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append(",\n"); }else{ sqlStr.append("NOT NULL,\n"); } } }// }// for end sqlStr.append("\n"); // 添加字段注釋 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append("comment on column "+ dbUserName +"."+ mapFirst.get("c0") +"."+ map.get("c1")+" is '"+ map.get("c5")+"';\n"); } return sqlStr.toString(); }else{ return ""; } } /** * PostgreSQL數據庫創建表SQL語句 * @param listSqlFiled * @return */ public static String createPSQL(List<Map<String, String>> listSqlFiled){ if(listSqlFiled != null && listSqlFiled.size()>0){ List<String> priKeyArray = new ArrayList<String>();// 主鍵集合 StringBuilder sqlStr = new StringBuilder(); // 獲取第一個map,存在表名 Map<String, String> mapFirst = listSqlFiled.get(0); sqlStr.append("create table "+ mapFirst.get("c0") +"(\n"); int length = listSqlFiled.size(); // 遍歷list集合 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append(""+ map.get("c1") +"\t "+ map.get("c2") +"\t"); // 是否為主鍵並且主鍵不能為空 if(map.get("c3").equalsIgnoreCase("Y")){ priKeyArray.add(map.get("c1")); sqlStr.append("NOT NULL,\n"); //表示結束了到最后一行了,並且只有一個主鍵 if(i >= length - 1 && priKeyArray.size() == 1){// 只有一個主鍵時 sqlStr.append("PRIMARY KEY ("+ priKeyArray.get(0) +")\n"); sqlStr.append(");\n"); // 表示到最后一行了,並且存在多個主鍵 }else if(i >= length - 1 && priKeyArray.size() > 1){// 多個主鍵時 sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append(""+ priKeyArray.get(k) +")\n"); }else{ sqlStr.append(""+ priKeyArray.get(k) +","); } } sqlStr.append(");\n"); } // 非主鍵,直接判斷是否允許為空 }else { // 表示沒有主鍵,並且到最后一個了 if(priKeyArray.size() <=0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append("\n"); }else{ sqlStr.append("NOT NULL\n"); } sqlStr.append(");\n"); // 表示有主鍵,並且是到最后一行了 }else if(priKeyArray.size() >0 && i >= length - 1){ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append(",\n"); }else{ sqlStr.append("NOT NULL,\n"); } // 表示只有一個主鍵 if(priKeyArray.size() == 1){ sqlStr.append("PRIMARY KEY ("+ priKeyArray.get(0) +")\n"); sqlStr.append(");\n"); // 表示有多個主鍵 }else{ sqlStr.append("PRIMARY KEY ("); // 遍歷主鍵 for(int k = 0; k < priKeyArray.size(); k ++){ // 到最后一個主鍵時 if(k == priKeyArray.size() - 1){ sqlStr.append(""+ priKeyArray.get(k) +")\n"); }else{ sqlStr.append(""+ priKeyArray.get(k) +","); } } sqlStr.append(");\n"); } // 沒有到最后一行繼續追加 }else{ if(map.get("c4").equalsIgnoreCase("Y")){// 允許為空 sqlStr.append(",\n"); }else{ sqlStr.append("NOT NULL,\n"); } } }// }// for end sqlStr.append("\n"); // 添加字段注釋 for(int i = 1; i < length; i ++){ // 遍歷map集合 Map<String, String> map = listSqlFiled.get(i); if(map.size() == 0){// 此處判斷不准確,最好的辦法就是把excle表的底部多余的行右鍵刪除掉 System.out.println("SQL語句不准確,請把excle表底部多余的行右鍵刪除掉!"); continue; } sqlStr.append("comment on column "+ mapFirst.get("c0") +"."+ map.get("c1")+" is '"+ map.get("c5")+"';\n"); } return sqlStr.toString(); }else{ return ""; } } /** * 測試 * @param args */ public static void main(String[] args) { try { // 測試MySQL數據庫 List<Map<String, String>> excelXReadMYSQL = ExcelUtil.excelXRead("F:/cs.xlsx",0); System.out.println(createMYSQL(excelXReadMYSQL)); // 測試SQLSERVER數據庫 List<Map<String, String>> excelXReadMSSQL = ExcelUtil.excelXRead("F:/cs.xlsx",1); System.out.println(createMSSQL(excelXReadMSSQL)); // 測試Oracle數據庫 List<Map<String, String>> excelXReadORCL = ExcelUtil.excelXRead("F:/cs.xlsx",2); System.out.println(createORACLE(excelXReadORCL, "SCOTT")); // 測試PostgreSQL數據庫 List<Map<String, String>> excelXRead = ExcelUtil.excelXRead("F:/cs.xlsx",3); System.out.println(createPSQL(excelXRead)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
使用注意:

多個表時:


程序空指針錯誤:

測試結果演示:PostgreSQL



create table T_ZHCS( F_ID SERIAL NOT NULL, F_CATA_ID VARCHAR(100) , F_SSJCK VARCHAR(100) , F_XXZYMC VARCHAR(100) , F_XXZYDM VARCHAR(100) , F_XXZYGS VARCHAR(100) , F_DATASET_TYPE VARCHAR(100) , F_REGION_CODE VARCHAR(100) , F_ORGAN_CODE VARCHAR(100) , F_XXZYTGF VARCHAR(100) , F_GXLX VARCHAR(100) , F_KFSX VARCHAR(100) , F_SRC_UPDATE_TIME TIMESTAMP , F_VALID_FLAG VARCHAR(100) , F_DATA_SOURCE_ID VARCHAR(100) , F_SYS_CREATE_TIME TIMESTAMP , F_SYS_UPDATE_TIME TIMESTAMP , F_SRC_TABLE_KEY VARCHAR(100) NOT NULL, PRIMARY KEY (F_ID,F_SRC_TABLE_KEY) ); comment on column T_ZHCS.F_ID is '主鍵'; comment on column T_ZHCS.F_CATA_ID is '資源目錄ID(主鍵)'; comment on column T_ZHCS.F_SSJCK is '所屬基礎庫'; comment on column T_ZHCS.F_XXZYMC is '信息資源名稱'; comment on column T_ZHCS.F_XXZYDM is '信息資源代碼'; comment on column T_ZHCS.F_XXZYGS is '信息資源格式'; comment on column T_ZHCS.F_DATASET_TYPE is '資源格式分類'; comment on column T_ZHCS.F_REGION_CODE is '區划編碼'; comment on column T_ZHCS.F_ORGAN_CODE is '信息資源提供方編碼'; comment on column T_ZHCS.F_XXZYTGF is '信息資源提供方名稱'; comment on column T_ZHCS.F_GXLX is '共享類型'; comment on column T_ZHCS.F_KFSX is '開放屬性'; comment on column T_ZHCS.F_SRC_UPDATE_TIME is '源系統數據更新時間'; comment on column T_ZHCS.F_VALID_FLAG is '數據有效標識'; comment on column T_ZHCS.F_DATA_SOURCE_ID is '數據來源'; comment on column T_ZHCS.F_SYS_CREATE_TIME is '系統登記時間'; comment on column T_ZHCS.F_SYS_UPDATE_TIME is '系統更新時間'; comment on column T_ZHCS.F_SRC_TABLE_KEY is '源表主鍵ID';
數據庫執行:

如有錯誤的地方望大牛們指出錯誤,大家共同進步
我只是把結果打在了控制台,其實大家可以拿着結果做其他操作,主要就是結果出來了,至於怎么玩,就看你們的了。哈哈
博客中演示的excle文件:
鏈接:https://pan.baidu.com/s/1prdb4Nk_8b5c7f-bi24U4A
提取碼:vhiz
