JDBC excel 導入數據庫




public class JImportExcelService extends CtrlServiceAdapter {
    
private String sql= "insert into RLZY_JNJDKPYTZ(F_ZZMC,F_XM,F_XB,F_WHCD,F_ZC,F_KPGZ,F_KPXGGZ,F_SFZH,F_LXDH,F_QZSJ,F_NF,F_NOTE,F_BH,F_GUID) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    int importCount = 0;

    @SuppressWarnings("unchecked")
    public JResponseObject doCtrlService(StubObject context, JParamObject param, HttpServletRequest request,
            HttpServletResponse resp) throws Exception {
        
        JResponseObject RO = null;
        
        importCount = 0;
        String realPath = request.getSession().getServletContext().getRealPath("/");
        String fileName = null;
        
        String zhhfileName = null;
        JConnection conn = null;
        try {
            int[] returnInt = { 0, 0 };
            param.setEnvValue("DBNO", "ZYYT_DB01");
            param.setEnvValue("DataBaseName", "ZYYT_DB01");
            conn = (JConnection) EAI.DAL.IOM("DBManagerObject", "GetDBConnection", param, this);
            conn.setAutoCommit(false);
            // 獲取上傳的文檔,並複製到工程中
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(41943040); // 設置緩衝區大小
            factory.setRepository(new File(realPath + "file" + File.separator + "cache"));// 設置緩衝區目錄

            SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddHHmmss");
            Date Time = new Date();
            String curTime = dateFormater.format(Time);
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(4194304000L); // 設置最大文件尺寸
            File file = new File(realPath + "file");
            if (!file.exists()) {
                file.mkdirs();
            }
            List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
            Iterator<FileItem> i = items.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                fileName = fi.getName();
                if (fileName != null) {
                    File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); // 解決文件名亂碼問題
                    String hzmString = fullFile.getName().substring(fullFile.getName().lastIndexOf(".") + 1,
                            fullFile.getName().length());
                    zhhfileName = curTime + "." + hzmString;
                    File savedFile = new File(realPath + "file", zhhfileName);
                    fi.write(savedFile);
                }
            }
            // 讀取文檔中的內容
            
            String fullFileName = realPath + "file" + File.separator + zhhfileName;
            if (fullFileName.endsWith(".xlsx")) {
                returnInt = parse07Excel(fullFileName, conn, param);
            } else if (fullFileName.endsWith(".xls")) {
                returnInt = parse03Excel(fullFileName, conn, param);
            } else {
                throw new Exception("您選擇的文件不是excel文件,請重新選擇!");
            }

            
            String    message = "導入成功!";
            RO = new JResponseObject(message, 1);
            
            request.setCharacterEncoding("gb2312");
            resp.setContentType("text/html;charset=gb2312");
            PrintWriter out = resp.getWriter();
            out.println("導入成功!"); // 向前臺傳遞的值
            out.flush();
            out.close();
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            request.setCharacterEncoding("gb2312");
            resp.setContentType("text/html;charset=gb2312");
            PrintWriter out = resp.getWriter();
            String errorString = "", errorMess = "";
            if (!"".equals(errorString)) {
                errorMess = errorString + "錯誤!";
            }
            
            out.println("導入失敗!" + errorMess + e.getMessage() + "請按照導入要求編輯文檔!"); // 向前臺傳遞的值
            out.flush();
            out.close();
        } finally {
            JDBResourceKit.release(conn);
            // 將文檔從工程中刪除
            DeleteFolder(realPath + "file");
        }

        return RO;
    }

    /*
     * 解析2003版本excel
     */

    public int[] parse03Excel(String path, JConnection conn, JParamObject param) throws Exception {

        PreparedStatement pstmt = null;
        Statement stmt = null;
        ResultSet rs = null;
        int[] returnInt = new int[2];
        int count = 0;

        try {
            
            stmt = conn.createStatement();
            String sql = "";
            InputStream stream = new FileInputStream(new File(path));
            HSSFWorkbook workbook = new HSSFWorkbook(stream); // 創建對Excel工作簿文件的引用
            
            // 獲取頁數遍歷
            for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
                if (null != workbook.getSheetAt(numSheets)) {
                    HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 獲得一個sheet
                    pstmt = conn.prepareStatement(sql);
                    // 從第3行開始遍歷
                    for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {
                        if (null != aSheet.getRow(rowNumOfSheet)) {
                            HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 獲得一行
                            count++;
                            // 解析每一行的每一個字段
                            for (int cellNumOfRow = 1; cellNumOfRow < aRow.getLastCellNum(); cellNumOfRow++) {
                                
                                pstmt.setString(cellNumOfRow, getColValue(aRow,cellNumOfRow));
                            }
                             pstmt.addBatch();
                            if (count % 50 == 0) {
                                int[] i = pstmt.executeBatch();
                                returnInt[0] += i.length;
                                pstmt.clearBatch();
                            }
                        }
                    }
                    int[] i = pstmt.executeBatch();
                    returnInt[0] += i.length;
                    returnInt[1] = count;
                    pstmt.clearBatch();
                }
            }
        } finally {
            JDBResourceKit.release(rs);
            JDBResourceKit.release(stmt);
            JDBResourceKit.release(pstmt);
        }
        return returnInt;
    }

    /*
     * 解析2007版本excel
     */

    public int[] parse07Excel(String path, JConnection conn, JParamObject param) throws Exception {
        PreparedStatement pstmt = null;
        Statement stmt = null;
        ResultSet rs = null;
        int[] returnInt = new int[2];
        int count = 0;
        try {
            
            stmt = conn.createStatement();
            InputStream stream = new FileInputStream(new File(path));
            XSSFWorkbook workbook = new XSSFWorkbook(stream); // 創建對Excel工作簿文件的引用
            
            String mBH = getMaxBH(conn);////獲取最大編號
            if (null==mBH || "".equals(mBH)) {
                mBH = "00000000";
            }
            
            int maxBh = Integer.parseInt(mBH);
            // 獲取頁數遍歷
            for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
                if (null != workbook.getSheetAt(numSheets)) {
                    XSSFSheet aSheet = workbook.getSheetAt(numSheets); // 獲得一個sheet
                    pstmt = conn.prepareStatement(sql);
                    for (int rowNumOfSheet = 2; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {//從第二行開始遍歷
                        if (null != aSheet.getRow(rowNumOfSheet)) {
                            XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 獲得一行
                            count++;
                            int bh = maxBh+aSheet.getLastRowNum()*numSheets + count;//每頁條數x頁數+第幾條
                            
                            String guid =    UUID.uuid(36);
                            pstmt.setString(13, parseBh(bh));
                            pstmt.setString(14, guid);
                            // 解析每一行的每一個字段
                            for (int cellNumOfRow = 1; cellNumOfRow < aRow.getLastCellNum(); cellNumOfRow++) {
                                pstmt.setString(cellNumOfRow, get07ColValue(aRow,cellNumOfRow));
                            }
                             pstmt.addBatch();
                            
                                if (count % 50 == 0) {
                                    int[] i = pstmt.executeBatch();
                                    returnInt[0] += i.length;
                                    pstmt.clearBatch();
                                }
                        }
                    }
                    int[] i = pstmt.executeBatch();
                    returnInt[0] += i.length;
                    returnInt[1] = count;
                    pstmt.clearBatch();
                }
            }
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("delete from RLZY_JNJDKPYTZ where F_BH not in(");
            sbSql.append("select mid from (select min(F_BH) mid from RLZY_JNJDKPYTZ group by F_SFZH,F_NF,F_QZSJ)" );
            sbSql.append(")");
            stmt.executeUpdate(sbSql.toString());
            
        }catch (Exception e) {
            throw e;
        } finally {
            JDBResourceKit.release(rs);
            JDBResourceKit.release(stmt);
            JDBResourceKit.release(pstmt);
            
        }
        return returnInt;
    }

    
    
    /**
     * 獲取最大編號
     * @param conn
     * @return
     * @throws Exception
     */
    public String getMaxBH(JConnection conn) throws Exception {
        Statement stmt = null;
        ResultSet rs = null;
        String bh = "";
        try {
            stmt = conn.createStatement();
            StringBuffer sb = new StringBuffer();
            sb.append("select Max(F_BH) as F_BH from RLZY_JNJDKPYTZ");
            rs = stmt.executeQuery(sb.toString());
            if (rs.next()) {
                bh = rs.getString("F_BH");
            }
            return bh;
        } catch (Exception e) {
            throw e;
        }finally {
            JDBResourceKit.release(rs);
            JDBResourceKit.release(stmt);
        }
    }
    
    /**
     * 對編號進行編譯
     * @param bh
     * @return
     */
    
    public String parseBh(int bh) {
        String F_BH = "";
        if (bh<10 && bh >= 0) {
            F_BH = "0000000" + bh;
        }else if(bh <100 && bh >= 10) {
            F_BH = "000000"+bh;
        }else if(bh <1000 && bh >= 100) {
            F_BH = "00000"+bh;
        }else if(bh <10000 && bh >= 1000) {
            F_BH = "0000"+bh;
        }else if(bh <100000 && bh >= 10000) {
            F_BH = "000"+bh;
        }else if(bh <1000000 && bh >= 100000) {
            F_BH = "00"+bh;
        }else if(bh <10000000 && bh >= 1000000) {
            F_BH = "0"+bh;
        }else {
            F_BH = ""+bh;
        }
        
        return F_BH;
    }
    
    /**
     * 根據路徑刪除指定的目錄或文件,無論存在與否
     * 
     * @param sPath
     *            要刪除的目錄或文件
     * @return 刪除成功返回 true,否則返回 false。
     */
    public boolean DeleteFolder(String sPath) {
        // 如果sPath不以文件分隔符結尾,自動添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir對應的文件不存在,或者不是一個目錄,則退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 刪除文件夾下的所有文件(包括子目錄)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 刪除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 刪除子目錄
            else {
                flag = DeleteFolder(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 刪除當前目錄
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 刪除單個文件
     * 
     * @param sPath
     *            被刪除文件的文件名
     * @return 單個文件刪除成功返回true,否則返回false
     */
    public boolean deleteFile(String sPath) {
        File file = new File(sPath);
        // 路徑爲文件且不爲空則進行刪除
        if (file.isFile() && file.exists()) {
            file.delete();
        }
        return true;
    }

    /*
     * 獲取03某列中某個單元格的值
     */
    public String getColValue(HSSFRow aRow, int num) {
        String field = "";
        if (null != aRow.getCell(num)) {
            HSSFCell aCell = aRow.getCell(num);
            if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                if (HSSFDateUtil.isCellDateFormatted(aCell)) { // 判斷是日期類型
                    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
                    Date dt = HSSFDateUtil.getJavaDate(aCell.getNumericCellValue());// 獲取成DATE類型
                    field = "" + dateformat.format(dt);
                } else {
                    field = "" + aCell.getNumericCellValue();
                }
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                field = "" + aCell.getBooleanCellValue();
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                field = "" + aCell.getStringCellValue();
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                field = "" + aCell.getCellFormula();
            }
        } else {
            field = "";
        }
        return field;
    }

    /*
     * 獲取07某列中某個單元格的值
     */
    public String get07ColValue(XSSFRow aRow, int num) {
        String field = "";
        if (null != aRow.getCell(num)) {
            XSSFCell aCell = aRow.getCell(num);
            if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                if (HSSFDateUtil.isCellDateFormatted(aCell)) { // 判斷是日期類型
                    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
                    Date dt = HSSFDateUtil.getJavaDate(aCell.getNumericCellValue());// 獲取成DATE類型
                    field = "" + dateformat.format(dt);
                } else {
                    field = "" + aCell.getNumericCellValue();
                }
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                field = "" + aCell.getBooleanCellValue();
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                field = "" + aCell.getStringCellValue();
            } else if (aCell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                field = "" + aCell.getCellFormula();
            }
        } else {
            field = "";
        }
        return field;
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章