poi完成excel文件上传和下载

一、 上传excel文件

1  spring-mvc.xml

    
		
		
		
	

 

2  jsp页面 - 导入excel代码块

选择导入文件:

    //导入
    $("#importBtn").click(function(){
        importLists();
    });

    /*导入数据*/
    function importLists(){
        //var clientid = $("#clientid").val();
        var FormDatas=new FormData($("#form-article-add")[0]);
        var fileName=$("#file").val();
        if(fileName == '') {
            alert('请选择文件!');
            return false;
        }
        //验证文件格式
        var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
        if (fileType != 'xls' && fileType != 'xlsx') {
            alert('文件格式不正确!');
            return false;
        }
        $.ajax({
            type:'post',
            url:'${rootUrl}importList.dox',
            async : false,
            cache : false,
            contentType : false,
            processData : false,
            data:FormDatas,
            success: function(data){
                data = JSON.parse(data);
                if(data == "1"){
                    alert("名单上传成功!");
                }
                if(data == "0"){
                    alert("名单上传失败!");
                }
                else{}
            },
            error : function(data){
                console.log(data.msg);
                alert("系统异常!");
            }
        });
    }

3  主要Java代码体

     /**
     * 导入excel
     * @return
     */
    @RequestMapping("importList.dox")
    @ResponseBody
    public String importList(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception {

        boolean b = BlackWhiteListlUtil.checkExcelFile(file);
        if(b == false){
            return "0";
        }
        Workbook workbook = BlackWhiteListlUtil.getWorkBook(file);
        if(workbook == null){
            return "0";
        }

        //判断是否成功
        Boolean success = true;

        List> list = new ArrayList<>();


        //获取第一个工作表
        Sheet sheet = workbook.getSheet("Sheet1");

        //获取sheet中第一行行号
        int firstRowNum = sheet.getFirstRowNum();
        //获取sheet中最后一行行号
        int lastRowNum = sheet.getLastRowNum();

        try {
            //循环插入数据
            for(int i=firstRowNum+1;i<=lastRowNum;i++){
                Row row = sheet.getRow(i);

                Cell optionClass = row.getCell(0);//名单种类
                Cell optionType = row.getCell(1);//名单类型
                Cell textimport = row.getCell(2);//名单内容
                Cell invalidtime = row.getCell(3);//失效时间

                if(optionClass!=null && optionType!=null && textimport!=null){

                    Map map = new HashMap<>();

                    optionClass.setCellType(Cell.CELL_TYPE_STRING);
                    String optionsKey = BlackWhiteListlUtil.getOptionClassKey(optionClass.getStringCellValue());
                    map.put("optionClass", optionsKey);

                    optionType.setCellType(Cell.CELL_TYPE_STRING);
                    String optionTypeKey = BlackWhiteListlUtil.getOptionTypeKey(optionType.getStringCellValue());
                    map.put("optionType", optionTypeKey);

                    textimport.setCellType(Cell.CELL_TYPE_STRING);
                    map.put("textimport", textimport.getStringCellValue());

                    invalidtime.setCellType(Cell.CELL_TYPE_STRING);
                    map.put("invalidtime", invalidtime.getStringCellValue());

                    list.add(map);

                }

            }

            //usersMapper.insert(list);//往数据库插入数据
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        } finally {
            workbook.close();
        }
        if(success == true){
            //将list存入redis
            JedisCluster jedis = RedisClusterClientUtils.getJedis();
            for (Map map : list) {
                String redisKey = BlackWhiteListlUtil.getRedisKey(map.get("optionClass"), map.get("optionType"));
                jedis.hset(redisKey + map.get("textimport"), "time", map.get("invalidtime")==null?"":map.get("invalidtime"));
            }
            return "1";
        }
        else{
            return "0";
        }
    }

 

4  工具类

    /**
     * 检查 excel文件格式是否正确
     */
    public static boolean checkExcelFile(MultipartFile file) throws Exception{
        //判断文件是否存在
        if(null == file){
            return false;
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
            return false;
        }

        return true;
    }

    /**
     * excel 生成通用的Workbook
     */
    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象,表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith("xls")){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith("xlsx")){
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * excel 判断cell数据类型
     */
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //把数字当成String来读,避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

 

需要导入的excel如图:

poi完成excel文件上传和下载_第1张图片

 

二 、导出excel

1  主要js代码块

     //导出
    $("#exportBtn").click(function(){

        var optionsClass = $("#selectClass").val();
        var optionsType = $("#selectType").val();

        if(optionsClass == ""){
            alert("请选择名单种类!");
        }
        if(optionsType == ""){
            alert("请选择名单类型!");
        }

        window.location.href = "${rootUrl}exportList.dox?optionsClass="+optionsClass+"&optionsType="+optionsType;
    });

2  主要Java代码块

    /**
     * 导出excel
     * @return
     */
    @RequestMapping("exportList.dox")
    public void exportLisr(String optionsClass, String optionsType, HttpServletResponse response, Integer eid){
        // 第一步,创建一个webbook,对应一个Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet("sheet1");

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
        HSSFRow row = sheet.createRow((int) 0);


        //查找数据
        String redisKey = BlackWhiteListlUtil.getRedisKey(optionsClass, optionsType);
        Set set= RedisClusterClientUtils.redisKeys(redisKey + "*");
        Iterator it = set.iterator();
        JedisCluster jedis = RedisClusterClientUtils.getJedis();

        //获得名单种类和名单类型的中文名
        String optionClassName = BlackWhiteListlUtil.getOptionClassName(optionsClass);
        String optionTypeName = BlackWhiteListlUtil.getOptionTypeName(optionsType);

        int i = 0;
        while (it.hasNext()) {

            row = sheet.createRow(i);

            if( i == 0){
                //设置标头
                row.createCell(0).setCellValue("名单种类");
                row.createCell(1).setCellValue("名单类型");
                row.createCell(2).setCellValue("名单内容");
                row.createCell(3).setCellValue("失效时间");

            }else{
                String keyStr = it.next();

                // 名单值
                String key = StringUtils.substringAfterLast(keyStr,"_");

                // 在redis获取其他属性
                String time = jedis.hget(keyStr, "time");

                row.createCell(0).setCellValue(optionClassName);
                row.createCell(1).setCellValue(optionTypeName);
                row.createCell(2).setCellValue(key);
                if (key.length() > 8){

                }
                if (StringUtils.isNotEmpty(time)){
                    row.createCell(3).setCellValue(time);

                }
                sheet.autoSizeColumn(0);
                sheet.autoSizeColumn(1);
                sheet.autoSizeColumn(2);
                sheet.autoSizeColumn(3);
            }

            i ++;
        }

        //下载
        ServletOutputStream out;
        try {
            out = response.getOutputStream();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
            Date date = new Date();
            String fileName = sdf.format(date)+".xls";
            response.reset();
            response.setContentType("application/msexcel");
            response.setHeader("Content-disposition", "attachment; filename="+fileName);
            wb.write(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

 

三、模板下载

    /**
     * 模板下载
     * @param response
     * @throws Exception
     */
    @RequestMapping("downListModel.dox")
    public void downListModel(HttpServletResponse response, HttpServletRequest request) throws Exception {

        InputStream inStream = BlackWhiteListController.class.getClassLoader().getResourceAsStream("/model.xls");

        // 下载本地文件
        String fileName = "model.xls"; // 文件的默认保存名
        // 读到流中
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

 

 

 

完成!

 

你可能感兴趣的:(poi完成excel文件上传和下载)