美文网首页
POI实现EXCEL导入

POI实现EXCEL导入

作者: 请叫我刚爷 | 来源:发表于2016-08-31 17:04 被阅读2888次

    Java开发过程中,有些需求需要实现Excel导入功能,具体就是Excel导入数据直接操作数据库,先将Excel导入实现方法贴出。实现过程如下。
    1、xml配置,本人使用较为成熟流行的ssm框架,即spring、springMvc、mybiats整合而成框架。所以需要在springMvc的xml配置中加入如下代码配置。这里非常重要

         <!-- 上传配置 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
                <property name="maxUploadSize" value="2097152"></property> 
                <property name="defaultEncoding" value="UTF-8" />  
            </bean> 
    

    2、jsp页面配置,上传必须使用from表单,且表单必须添加属性enctype="multipart/form-data" onsubmit="return check();"并在上传input中添加accept="xls/xlsx" size="50"。用于限制上传文件格式。

        <form action="/Matton/batchimport.do" method="post" enctype="multipart/form-data" name="batchAdd" onsubmit="return check();">
            <div class="col-lg-4">
                <input id="excel_file" type="file" name="filename" accept="xls/xlsx" size="50"/>
            </div>
            <input id="excel_button" class="btn btn-success col-lg-1" type="submit" value="导入Excel"/>
           <%--  <font id="importMsg" color="red"><%=importMsg%></font><input type="hidden"/> --%>  
        </form>
    

    3、xml配置和jsp配置已经完成,现在就是后台代码(@RequestParam("filename") MultipartFile file这里的filename需与from表单中的input的name一致。MultipartFile 就是刚刚xml配置启动的。所以xml配置不可或缺。

        /**
         * excel批量导入
         * @param file
         * @param request
         * @param response
         * @return
         * @throws Exception
         */
        @RequestMapping(value = "batchimport.do", method = RequestMethod.POST)
        public String batchimport(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
         //   String a = "C:\Users\lg\Desktop\1.xlsx";
            //获取路径
            if(file==null) return null;
            //文件名
            String name=file.getOriginalFilename();
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload"+"\\"  
                    + file.getOriginalFilename();  
            long size=file.getSize();
            if(name==null || ("").equals(name) && size==0) return null;
            try {
                InputStream in = file.getInputStream();
              //调用Service,将数据插入Excel
                int i=poiService.batchImport(filePath,file);
                if(i>0){
                     String Msg ="导入成功";
                     avg();
                     request.getSession().setAttribute("msg",Msg);
                }else{
                     String Msg ="导入失败";
                     request.getSession().setAttribute("msg",Msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                excel();
            }
        //  return null; 
            return "forward:/jsp/excel/excel.jsp";
        }
    

    Service实现,将调用实现类。

        /**
         * excel倒库
         * @param name
         * @param file
         * @return
         */
        public int batchImport(String name,MultipartFile file);
    

    Service实现类,调动实现方法。

        /**
         *批量导入 
         */
        public int batchImport(String name,MultipartFile file) {
                    //这个是Excel导入的实现工具类。但不是直接导入数据库
                    //是将Excel数据分解成能够导入数据库的数据。
            ExelUtil readExcel=new ExelUtil();
            List<MeatModel> userList=readExcel.getExcelInfo(name,file);
            if("".equals(userList) || userList.size() < 1){
                return 0;
            }else{
              //这才是导入操作
                 return meatMapper.batchInsertStudent(userList);
            }
         }
    

    导入工具类:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.DateFormat;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.apache.commons.fileupload.disk.DiskFileItem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFDataFormat;
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellStyle;
    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.XSSFWorkbook;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.subject.Subject;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import com.matton.model.LoginUserModel;
    import com.matton.model.MeatModel;
    import com.matton.model.Student;
    import com.sun.org.apache.xml.internal.serializer.utils.Utils;
    
    
    public class ExelUtil {
    
        //总行数
        private int totalRows = 0;  
       
        //总条数
        private int totalCells = 0; 
        
        //错误信息接收器
        private String errorMsg;
              
        //构造方法
        public ExelUtil(){}
        
        //得到总行数
        public int getTotalRows()  { return totalRows;} 
        
        //得到总列数
        public int getTotalCells() {  return totalCells;} 
        
        public String getErrorInfo() { return errorMsg; }  
        
      /**
       * 描述:验证EXCEL文件
       * @param filePath
       * @return
       */
      public boolean validateExcel(String filePath){
          /** 检查文件是否存在 */  
    /*      File file = new File(filePath);  
          boolean a = file.exists();
          if (file == null || !file.exists()) {  
            errorMsg = "文件不存在";  
              return false;  
          } */ 
          
          if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){  
              errorMsg = "文件名不是excel格式";  
              return false;  
          }  
           
            return true;
      }
        
      
      /**描述 :读EXCEL文件
       * @param fielName
       * @return
       */
      public List<MeatModel> getExcelInfo(String fileName,MultipartFile Mfile){
          
          //把spring文件上传的MultipartFile转换成File
           CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; 
           DiskFileItem fi = (DiskFileItem)cf.getFileItem();
          File file = fi.getStoreLocation();
          List<MeatModel> userList=new ArrayList<MeatModel>();
    //  fileName = "E:/ruanjian/apache-tomcat-6.0.41 -3/webapps/Matton/upload/1.xlsx";
          
          InputStream is = null;  
          try{
              //验证文件名是否合格
              if(!validateExcel(fileName)){
                  return null;
              }
              //判断文件时2003版本还是2007版本
              boolean isExcel2003 = true; 
              if(WDWUtil.isExcel2007(fileName)){
                  isExcel2003 = false;  
              }
              is = new FileInputStream(file);
              userList=getExcelInfo(is, isExcel2003); 
              is.close();
          }catch(Exception e){
              e.printStackTrace();
          }
          finally{
              if(is !=null)
              {
                  try{
                      is.close();
                  }catch(IOException e){
                      is = null;    
                      e.printStackTrace();  
                  }
              }
          }
          return userList;
      }
      /**
       * 此方法两个参数InputStream是字节流。isExcel2003是excel是2003还是2007版本
       * @param is
       * @param isExcel2003
       * @return
       * @throws IOException
       */
      public  List<MeatModel> getExcelInfo(InputStream is,boolean isExcel2003){
          
           List<MeatModel> userList=null;
           try{
               /** 根据版本选择创建Workbook的方式 */
               Workbook wb = null;
               //当excel是2003时
               if(isExcel2003){
                   wb = new HSSFWorkbook(is);
               }else{
                   wb = new XSSFWorkbook(is);
               }
               userList=readExcelValue(wb);
           }
           catch (IOException e)  {  
               e.printStackTrace();  
           }  
           return userList;
      }
      /**
       * 读取Excel里面的信息
       * @param wb
       * @return
       */
      private List<MeatModel> readExcelValue(Workbook wb){ 
           //得到第一个shell  
           Sheet sheet=wb.getSheetAt(0);
           //得到Excel的行数
           this.totalRows=sheet.getPhysicalNumberOfRows();
           //得到Excel的列数(前提是有行数)
           if(totalRows>=1 && sheet.getRow(0) != null){
                this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
           }
           List<MeatModel> userList=new ArrayList<MeatModel>();
           MeatModel meat = null ;
           //获取当前用户id
              Subject currentUser = SecurityUtils.getSubject();
              Session session = currentUser.getSession();
              session.getAttribute("currentUser");
              LoginUserModel loginUserModel = (LoginUserModel) session.getAttribute("currentUser");
           
           
           System.out.println(this.totalRows+"行行航哈哈哈哈哈哈哈哈哈哈哈哈");
           System.out.println(this.getTotalCells()+"行行航哈哈哈哈哈哈哈哈哈哈哈哈");
           /** 循环Excel的行,然后循环列,即先循环行,再循环列 */  
           for (int r = 1; r < this.totalRows; r++) {  
               Row row = sheet.getRow(r);  
               if (row == null){  
                   continue;  
               }  
              // List<String> rowLst = new ArrayList<String>();  
               meat = new MeatModel();
               /** 循环Excel的列 */  
               for (int c = 0; c < this.getTotalCells(); c++){  
                   Cell cell = row.getCell(c);  
                   String cellValue = getCellTypes(cell);  
                   
                   GenerateSequenceUtil strid = new GenerateSequenceUtil();
                   meat.setWaterId(strid.generateSequenceNo());
                   if(c == 0){
                       meat.setInsertData(cellValue);
                   }else if(c == 1){
                       meat.setMeatNum(cellValue); 
                   } else if(c == 2){
                       meat.setEmptyCupWeight(cellValue);//空杯子质量
                   } else if(c == 3){
                       meat.setWaterCupWeight(cellValue);//空杯+鲜肉质量
                   } else if(c == 4){
                       meat.setMeatWeight(cellValue);//鲜肉质量
                   } else if(c == 5){
                       meat.setNoWaterMeatWeight(cellValue);//空干后的肉+杯子的质量
                   } else if(c == 6){
                       if("".equals(meat.getWaterCupWeight()) || null == meat.getWaterCupWeight() ||
                               "".equals(meat.getNoWaterMeatWeight()) || null == meat.getNoWaterMeatWeight() ||  
                               "".equals(meat.getMeatWeight()) || null == meat.getMeatWeight() 
                               ){
                           //如果该字段存在值则使用,不存在放空
                           if("".equals(cellValue) || null == cellValue ){
                               cellValue = "";
                           }else{
                               DecimalFormat  df = new DecimalFormat("0.0000");
                             cellValue = df.format(cellValue);
                           }
                       }else{
                       double WaterCupWeight = Double.parseDouble(meat.getWaterCupWeight());
                       double NoWaterMeatWeight = Double.parseDouble(meat.getNoWaterMeatWeight());
                       double MeatWeight = Double.parseDouble(meat.getMeatWeight());
                       double water = ((WaterCupWeight - NoWaterMeatWeight  ) / MeatWeight);
                      DecimalFormat  df = new DecimalFormat("0.0000");
                     cellValue = df.format(water);
                       }
                      cellValue = String.valueOf(cellValue);
                       meat.setWater(cellValue);//水分
                   } else if(c == 7){
                       meat.setWateravg(cellValue);//平均值
                   }
     
                  meat.setUserId(loginUserModel.getUserId());
                  
               }
               userList.add(meat);
           }
           
        return userList;
      }
      //判断Excel倒入数据类型,转换为数据库可识别的数据类型
      public String getCellTypes(Cell cell){
          String cellValue = null;
          if (null != cell) {  
              // 以下是判断数据的类型  
              switch (cell.getCellType()){  
              case HSSFCell.CELL_TYPE_NUMERIC: // 数字  
                // 处理日期格式、时间格式
                  if (HSSFDateUtil.isCellDateFormatted(cell)) {
                      Date d = cell.getDateCellValue();
                      DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
                      cellValue = formater.format(d);
                  }
                  else{ 
                      cellValue = cell.getNumericCellValue() + ""; 
                  }  
                        
                        
                  break;  
    
              case HSSFCell.CELL_TYPE_STRING: // 字符串  
                  cellValue = cell.getStringCellValue();  
                  break;  
    
              case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
                  cellValue = cell.getBooleanCellValue() + "";  
                  break;  
    
              case HSSFCell.CELL_TYPE_FORMULA: // 公式  
                 // cellValue = cell.getCellFormula() + "";  
                  try {
                      DecimalFormat  df = new DecimalFormat("0.0000");
                      cellValue = String.valueOf(df.format(cell.getNumericCellValue()));
                      
                  } catch (IllegalStateException e) {
                      cellValue = String.valueOf(cell.getRichStringCellValue());
                         }
                  break;  
    
              case HSSFCell.CELL_TYPE_BLANK: // 空值  
                  cellValue = "";  
                  break;  
    
              case HSSFCell.CELL_TYPE_ERROR: // 故障  
                  cellValue = "非法字符";  
                  break;  
    
              default:  
                  cellValue = "未知类型";  
                  break;  
              }  
          }  
        return cellValue;
      }
      
    }
    

    Excel文件格式判断,判断Excel是07版还是10版

           // 验证是否是excel2003
          public static boolean isExcel2003(String filePath)  {  
              return filePath.matches("^.+\\.(?i)(xls)$");  
          }  
    
           //验证是否是excel2007 
          public static boolean isExcel2007(String filePath)  {  
              return filePath.matches("^.+\\.(?i)(xlsx)$");  
          }  
    

    Excel导入至此完成。
    本人于2016年毕业,小白一枚,经验不足。各位看官如有问题,请百度。小白我也是一步一步百度而来。小白QQ群571669420,静请打扰;

    相关文章

      网友评论

          本文标题:POI实现EXCEL导入

          本文链接:https://www.haomeiwen.com/subject/bczqettx.html