使用poi实现Excel导入功能,数据库基于oracle(下)

来源:互联网 发布:数字锁相环 算法 编辑:程序博客网 时间:2024/06/15 09:03

上次我们说了导入的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导入就差不多完成了,如果大家还有更好的技术实现,欢迎指教。

原创粉丝点击