java将Excel文件上传并解析为List数组

前端

//导入excel文件
            layui.use('upload', function() {
                var upload =layui.upload;
             
                //指定允许上传的文件类型
                var uploadInst = upload.render({
                  elem: '#btn_import'
                  ,url: contextPath + "/service/eoms/ordermgt/importExcel.ilf"
                  ,accept: 'file' //普通文件
                  ,done: function(res){
                      console.log(res);
                      alert("success");
                   }
                });
            });

java controller

//导入excel表格并解析
        @RequestMapping(value = "/importExcel.ilf")
        @ResponseBody
        public JSONObject importExcel(HttpServletRequest request,HttpServletResponse response,MultipartFile file) throws IOException {
            String originalFilename = file.getOriginalFilename();
            String type = file.getContentType();
            //originalFilename = UUID.randomUUID().toString()+originalFilename;
            System.out.println("目标文件名称:"+originalFilename+",目标文件类型:"+type);
            
            InputStream is = file.getInputStream();
            //Workbook createWorkbook = importExcel.createWorkbook(is, type);
            
            //
            ImportExcel importExcel = new ImportExcel();
            List<Object> list= importExcel.importDataFromExcel( is, originalFilename);
            for(int i = 0;i<list.size();i++){
                System.out.println(list.get(i).toString());
            }
            
            
            JSONObject json=new JSONObject();
            
            return json;
        }
/** 
 * @ClassName: ExcelUtil 
 * @Description: Excel导入工具类 
 * @date    
 */
public class ImportExcel {
    private static final Logger logger = Logger.getLogger(ImportExcel.class);

    /** 
     * @Title: createWorkbook 
     * @Description: 判断excel文件后缀名,生成不同的workbook      * @param @param is
     * @param @param excelFileName
     * @param @return
     * @param @throws IOException
     * @return Workbook
     * @throws 
     */
    public Workbook createWorkbook(InputStream is,String excelFileName) throws IOException{
        if (excelFileName.endsWith(".xls")) {
            return new HSSFWorkbook(is);
        }else if (excelFileName.endsWith(".xlsx")) {
            return new XSSFWorkbook(is);
        }
        return null;
    }

    /** 
     * @Title: getSheet 
     * @Description: 根据sheet索引号获取对应的sheet
     * @param @param workbook
     * @param @param sheetIndex
     * @param @return
     * @return Sheet
     * @throws 
     */
    public Sheet getSheet(Workbook workbook,int sheetIndex){
        return workbook.getSheetAt(0);        
    }


    public List<Object> importDataFromExcel(InputStream is,String excelFileName){
        List<Object> list = new ArrayList<Object>();
        try {
            //创建工作簿
            Workbook workbook = this.createWorkbook(is, excelFileName);
            //创建工作表sheet
            Sheet sheet = this.getSheet(workbook, 0);
            //获取sheet中数据的行数
            int rows = sheet.getPhysicalNumberOfRows();
            //获取表头单元格个数
            int cells = sheet.getRow(0).getPhysicalNumberOfCells();
            
            for (int i = 1; i < rows; i++) {//第一行为标题栏,从第二行开始取数据   
                
                //利用反射,给JavaBean的属性进行赋值
                ImportExcelFile vo = new ImportExcelFile();
                Field[] fields = vo.getClass().getDeclaredFields();
                
                Row row = sheet.getRow(i);
                int index = 0;
                while (index < cells) {
                    Cell cell = row.getCell(index);
                    if (null == cell) {
                        cell = row.createCell(index);
                    }
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    String value = null == cell.getStringCellValue()?"":cell.getStringCellValue();

                    Field field = fields[index];
                    String fieldName = field.getName();
                    String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                    Method setMethod = vo.getClass().getMethod(methodName, new Class[]{String.class});
                    setMethod.invoke(vo, new Object[]{value});
                    index++;
                }
                 if (isHasValues(vo)) {//判断对象属性是否有值
                    list.add(vo);
                    //vo.getClass().getConstructor(new Class[]{}).newInstance(new Object[]{});//重新创建一个vo对象
                }

            }
        } catch (Exception e) {
            logger.error(e);
        }finally{
            try {
                is.close();//关闭流
            } catch (Exception e2) {
                logger.error(e2);
            }
        }
        return list;

    }

    /** 
     * @Title: isHasValues 
     * @Description: 判断一个对象所有属性是否有值,如果一个属性有值(分空),则返回true
     * @param @param object
     * @param @return
     * @return boolean
     * @throws 
     */
    public boolean isHasValues(Object object){
        Field[] fields = object.getClass().getDeclaredFields();
        boolean flag = false;
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            String methodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
            Method getMethod;
            try {
                getMethod = object.getClass().getMethod(methodName);
                Object obj = getMethod.invoke(object);
                if (null != obj && !"".equals(obj)) {
                    flag = true;
                    break;
                }
            } catch (Exception e) {
                logger.error(e);
            }                 
        }
        return flag;

    }

dao层

package com.inspur.om.order.data;

public class ImportExcelFile {
    private String orderId;
    private String orderName;
    private String orderType;
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public String getOrderName() {
        return orderName;
    }
    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }
    public String getOrderType() {
        return orderType;
    }
    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }
    @Override
    public String toString() {
        return "ImportExcelFile [orderId=" + orderId + ", orderName="
                + orderName + ", orderType=" + orderType + "]";
    }
    
}

 

posted @ 2018-08-13 15:51  biubiubiuo  阅读(4242)  评论(1编辑  收藏  举报