1. 程式人生 > >使用poi實現Excel匯入功能,資料庫基於oracle(下)

使用poi實現Excel匯入功能,資料庫基於oracle(下)

上次我們說了匯入的service以及controller,jsp的一些程式碼的實現,這回趁著有時間,把最後的匯入Util類實現給大家。
1、util類:ReadExcel.java

public class ReadExcel {

        //總行數
        private int totalRows = 0;
        //總條數
        private int totalCells = 0;
        //錯誤資訊接收器
        private String errorMsg;
        //獲得總行數
        public int getTotalRows
(){return totalRows;}; //構造方法 public ReadExcel(){} //獲得總列數 public int getTotalCells (){return totalCells;}; //獲取錯誤資訊 public String getErrorInfo(){return errorMsg;}; /*讀取EXCEL檔案,獲取資訊集合-------*/ public List<OutUrmList> getExcelInfo(MultipartFile myFile,String Mid){ List<OutUrmList> urmList = new
ArrayList<OutUrmList>(); String fileName =myFile.getOriginalFilename();//獲取檔名 try { if(!ValidateExcel(fileName)){//驗證檔名是否合格 return null; } boolean isExcel2003 = true;//根據檔名判斷EXCEL版本:2003/2007 if(isExcel2007(fileName)){ isExcel2003 = false
; } urmList = createExcel(myFile.getInputStream(),isExcel2003,Mid,myFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return urmList; } /* * 根據EXCEL裡面的內容讀取客戶資訊 * * */ public List<OutUrmList> createExcel(InputStream is,boolean isExcel2003,String Mid,MultipartFile myFile){ List<OutUrmList> urmList =new ArrayList<OutUrmList>(); Workbook wb = null; try { wb = WorkbookFactory.create(myFile.getInputStream()); } catch (InvalidFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if(isExcel2003){//當EXCEL是2003時,建立EXCEL2003 // try { // wb = new HSSFWorkbook(is); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // }else{//當EXCEL是2007時,建立EXCEL2007 // try { // wb = new XSSFWorkbook(is); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } urmList = ReadExcelValue(wb,Mid);//讀取Excel裡面的資訊 return urmList; } /* * 讀取EXCEL的客戶資訊 * * */ public List<OutUrmList> ReadExcelValue(Workbook wb,String Mid){ //得到第一個shell Sheet sheet = wb.getSheetAt(0); //單元格的值 String cellvalue = ""; //得到EXCEL的行數 this.totalRows = sheet.getPhysicalNumberOfRows(); //得到EXCEL的列數(前提是有行數) if(totalRows>1&&sheet.getRow(0)!=null){ this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } List<OutUrmList> urmlist = new ArrayList<OutUrmList>(); List<OutUrmList> urmlist1 = new ArrayList<OutUrmList>(); //迴圈EXCEL的行數,得到第一行的標題文字 for(int o = 0;o<totalRows;o++){ Row row = sheet.getRow(o); if(row == null){ continue; } //取到Excel的列名,校驗是否相等,如果是則可以繼續匯入 if(o==0){ for(int c = 0;c<totalCells;c++){ Cell cell = row.getCell(c); if(c == 0){ if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){ cellvalue = cell.getStringCellValue().replaceAll("'", "''"); } if(!"單號".equals(cellvalue)){ return urmlist1; } } if(c == 1){ if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){ cellvalue = cell.getStringCellValue().replaceAll("'", "''"); } if(!"性別".equals(cellvalue)){ return urmlist1; } } if(c == 2){ if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){ cellvalue = cell.getStringCellValue().replaceAll("'", "''"); } if(!"型別".equals(cellvalue)){ return urmlist1; } } } continue; } } //迴圈EXCEL的行數 for(int r = 1;r<totalRows;r++){ Row row = sheet.getRow(r); if(row == null){ continue; } OutUrmList outUrmList = new OutUrmList(); //迴圈EXCEL的列數 for(int c = 0;c<totalCells;c++){ Cell cell = row.getCell(c); if(cell != null&&totalCells==3){ if(c == 0){ // 判斷當前Cell的Type switch (cell.getCellType()) { // 如果當前Cell的Type為NUMERIC case HSSFCell.CELL_TYPE_NUMERIC: { short format = cell.getCellStyle().getDataFormat(); if(format == 14 || format == 31 || format == 57 || format == 58){ //excel中的時間格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = DateUtil.getJavaDate(value); cellvalue = sdf.format(date); outUrmList.setFormNo(cellvalue); } // 判斷當前的cell是否為Date else if (HSSFDateUtil.isCellDateFormatted(cell)) { //先註釋日期型別的轉換,在實際測試中發現HSSFDateUtil.isCellDateFormatted(cell)只識別2014/02/02這種格式。 // 如果是Date型別則,取得該Cell的Date值 // 對2014-02-02格式識別不出是日期格式 Date date = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); cellvalue= formater.format(date); outUrmList.setFormNo(cellvalue); } else { // 如果是純數字 // 取得當前Cell的數值 cellvalue = NumberToTextConverter.toText(cell.getNumericCellValue()); outUrmList.setFormNo(cellvalue); } break; } // 如果當前Cell的Type為STRIN case HSSFCell.CELL_TYPE_STRING: // 取得當前的Cell字串 cellvalue = cell.getStringCellValue().replaceAll("'", "''"); outUrmList.setFormNo(cellvalue); break; case HSSFCell.CELL_TYPE_BLANK: cellvalue = null; outUrmList.setFormNo(cellvalue); break; // 預設的Cell值 default:{ cellvalue = " "; } } } if(c == 1){ // 判斷當前Cell的Type switch (cell.getCellType()) { // 如果當前Cell的Type為NUMERIC case HSSFCell.CELL_TYPE_NUMERIC: { short format = cell.getCellStyle().getDataFormat(); if(format == 14 || format == 31 || format == 57 || format == 58){ //excel中的時間格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = DateUtil.getJavaDate(value); cellvalue = sdf.format(date); outUrmList.setLogNo(cellvalue); } // 判斷當前的cell是否為Date else if (HSSFDateUtil.isCellDateFormatted(cell)) { //先註釋日期型別的轉換,在實際測試中發現HSSFDateUtil.isCellDateFormatted(cell)只識別2014/02/02這種格式。 // 如果是Date型別則,取得該Cell的Date值 // 對2014-02-02格式識別不出是日期格式 Date date = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); cellvalue= formater.format(date); outUrmList.setLogNo(cellvalue); } else { // 如果是純數字 // 取得當前Cell的數值 cellvalue = NumberToTextConverter.toText(cell.getNumericCellValue()); outUrmList.setLogNo(cellvalue); } break; } // 如果當前Cell的Type為STRIN case HSSFCell.CELL_TYPE_STRING: // 取得當前的Cell字串 cellvalue = cell.getStringCellValue().replaceAll("'", "''"); outUrmList.setLogNo(cellvalue); break; case HSSFCell.CELL_TYPE_BLANK: cellvalue = null; outUrmList.setLogNo(cellvalue); break; // 預設的Cell值 default:{ cellvalue = " "; } } } if(c == 2){ // 判斷當前Cell的Type switch (cell.getCellType()) { // 如果當前Cell的Type為NUMERIC case HSSFCell.CELL_TYPE_NUMERIC: { short format = cell.getCellStyle().getDataFormat(); if(format == 14 || format == 31 || format == 57 || format == 58){ //excel中的時間格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = DateUtil.getJavaDate(value); cellvalue = sdf.format(date); outUrmList.setFormType(cellvalue); } // 判斷當前的cell是否為Date else if (HSSFDateUtil.isCellDateFormatted(cell)) { //先註釋日期型別的轉換,在實際測試中發現HSSFDateUtil.isCellDateFormatted(cell)只識別2014/02/02這種格式。 // 如果是Date型別則,取得該Cell的Date值 // 對2014-02-02格式識別不出是日期格式 Date date = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); cellvalue= formater.format(date); outUrmList.setFormType(cellvalue); } else { // 如果是純數字 // 取得當前Cell的數值 cellvalue = NumberToTextConverter.toText(cell.getNumericCellValue()); outUrmList.setFormType(cellvalue); } break; } // 如果當前Cell的Type為STRIN case HSSFCell.CELL_TYPE_STRING: // 取得當前的Cell字串 cellvalue = cell.getStringCellValue().replaceAll("'", "''"); outUrmList.setFormType(cellvalue); break; case HSSFCell.CELL_TYPE_BLANK: cellvalue = null; outUrmList.setFormType(cellvalue); break; // 預設的Cell值 default:{ cellvalue = " "; } } } } } //新增到LIST //outUrmList.setExcelInfoId(IdGen.uuid()); //outUrmList.setMid(Mid); urmlist.add(outUrmList); } System.out.println(urmlist); return urmlist; } /** * 驗證EXCEL檔案 * */ public boolean ValidateExcel(String filePath){ if(filePath == null || !(isExcel2003(filePath)||isExcel2007(filePath))){ errorMsg = "檔名不是excel格式!"; return false; } return true; } /** 是否是2003的EXCEL,返回true的就是2003 * */ public static boolean isExcel2003(String filePath){ return filePath.matches("^.+\\.(?i)(xls)$"); } /** 是否是2003的EXCEL,返回true的就是2003 * */ public static boolean isExcel2007(String filePath){ return filePath.matches("^.+\\.(?i)(xlsx)$"); } }

2、針對資料庫是Oracle的迴圈插入實現:採用forEach迴圈插入資料
—mapper.xml (Oracle)

<insert id="insertExcelInfo" parameterType="java.util.List">
        INSERT INTO bbmu_out_urm_list(
            id,
            m_id,
            FORM_NO,
            FORM_TYPE,
            LOG_NO,
            godown_entry_id
        ) SELECT 
             A.*
             FROM (
        <foreach collection="list" item="item" index="index" separator="UNION ALL">//collection這裡就寫list,不是你自己自定義的list,注意的是:separator="UNION ALL"
          SELECT
            #{item.excelInfoId} id,
            #{item.Mid} m_id,
            #{item.formNo} FORM_NO,
            #{item.formType} FORM_TYPE,
            #{item.logNo} LOG_NO,
            #{item.godownEntryId} godown_entry_id
            FROM DUAL
        </foreach>
        ) A
    </insert>

基本上,一個基於poi的EXCEL匯入就差不多完成了,如果大家還有更好的技術實現,歡迎指教。