package com.interact.util; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * 讀取excel生成sql腳本 * qcq0807 */ public class InsertDataUtil { public static void main(String[] args) throws Exception { InsertDataUtil in = new InsertDataUtil(); // String path = "C:\\Users\\Administrator\\Desktop\\8088需求記錄\\user_qcq.xls"; String path = "C:\\Users\\Administrator\\Desktop\\8088需求記錄\\org_qcq.xls"; //表格的地址 //String tabaleName = "t_user"; String tabaleName = "t_org"; //表名 in.insert(path, tabaleName); } /** * @param path 要解析的excel文件路徑 * @param dataTable 要寫入到數據庫中的表名 * @throws BiffException * @throws IOException */ public void insert(String path, String dataTable) throws BiffException, IOException { File file = new File(path); // 創建新的Excel 工作簿 Workbook rwb = null; rwb = Workbook.getWorkbook(file); String toFileName = "D:/org_qcq.sql"; //寫出的文件地址和名稱 //String toFileName = "D:/user_qcq.sql"; // 得到工作簿中的第一個表索引即為excel下的sheet1,sheet2,sheet3... Sheet sheet = rwb.getSheets()[0]; int rsColumns = sheet.getColumns();// 列數 int rsRows = sheet.getRows();// 行數 String simNumber = "";//每個單元格中的數據 String sqlFinel = ""; String str = "";//拼接要插入的列 for (int j = 0; j < rsColumns ; j++) { Cell cell = sheet.getCell(j, 0); simNumber = cell.getContents(); if (j == rsColumns - 1) { str += simNumber; } else { str += simNumber + ","; } } for (int i = 1; i < rsRows; i++) { String id = IdGenerator.getId(); String sql = "insert into " + dataTable + "(" + str + ") values(";//拼接sql sql += "'" + id + "'"; //添加用戶時 需要添加角色 默認都是管理員 //String sql1 = "insert into user_role_relation (user_id,role_id) values("; //sql1 += "'" + id + "','" + "0158b84de66a0002');"; //管理員id去現場重新編寫 切記切記!!! //System.out.println(sql1); for (int j = 0; j < rsColumns; j++) { Cell cell = sheet.getCell(j, i); simNumber = cell.getContents(); if (j == rsColumns - 1) { sql += "'" + simNumber + "'"; } else { if(j == 0){ //id需要進行處理 sql += ","; }else{ sql += "'" + simNumber + "',"; } } } sql += " );"; FileWriter fileWriter = null; try { fileWriter = new FileWriter(toFileName,true);//創建文本文件 true屬性不覆蓋 fileWriter.write(sql + "\r\n");//寫入 \r\n換行 //fileWriter.write(sql1 + "\r\n");//寫入 \r\n換行 fileWriter.flush(); fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(sql); } } }
表格需要有一定的格式(其實格式主要是第一行,要跟數據庫字段對應起來)
沒有做太多處理,參考鏈接:https://shenhaocric.iteye.com/blog/663802