1. 程式人生 > >SpringMVC 下載Excel模板和匯入資料

SpringMVC 下載Excel模板和匯入資料

一:模板下載功能

頁面:

    window.location.href="/test/downloadModel?id="+result;
id是uuid生成的一個請求ID;

        java:        

    @ResponseBody
    @RequestMapping(value ="/downloadModel", method = {RequestMethod.GET})
    public ResponseEntity<byte[]> downloadModel(@RequestParam("id") String id,HttpServletRequest req) throws InterruptedException {
        RedisClient.getInstance().put("progress_"+id,0,60*60);
        ResponseEntity<byte[]> download = fileService.download("files/cardKind/cardKindModel.xlsx", id, req);
        RedisClient.getInstance().put("progress_"+id,100,60*60);
        return download;
    }

 download方法
@Override
    public ResponseEntity<byte[]> download(String path, String id, HttpServletRequest req) {
        downloadLogger.info("【檔案下載】 download --> 執行開始,請求檔案相對路徑:" + path);
        File file = null;
        try {
//            Resource resource = new ClassPathResource(path);
//            file = resource.getFile();
//            file=new File("c:/1.xlsx");
            Resource resource=new ServletContextResource(req.getServletContext(),"file/cardKindModel.xlsx");
            file = resource.getFile();
//        } catch (IOException e) {
        } catch (Exception e) {
            downloadLogger.info("【檔案下載】 download -->執行異常,無法載入到服務端檔案,請求檔案相對路徑:" + path, e);
            return null;
        }
        RedisClient.getInstance().put("progress_" + id, 10, 60 * 60);
        String fileName = null;
        try {
            fileName = new String(file.getName().getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            downloadLogger.info("【檔案下載】 download -->執行異常,無法解析服務端檔案,請求檔案相對路徑:" + path, e);
            return null;
        }

        RedisClient.getInstance().put("progress_" + id, 20, 60 * 60);
        HttpHeaders header = new HttpHeaders();
        header.setContentDispositionFormData("attachment", fileName);
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        RedisClient.getInstance().put("progress_" + id, 30, 60 * 60);
        byte[] res = null;
        try {
            res = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            downloadLogger.info("【檔案下載】 download -->執行異常,解析服務端檔案為位元組陣列異常,請求檔案相對路徑:" + path, e);
            return null;
        }
        RedisClient.getInstance().put("progress_" + id, 90, 60 * 60);
        return new ResponseEntity<byte[]>(res, header, HttpStatus.CREATED);
    }

ps: 模板檔案在webapp目錄下,可以使用ServletContextResource獲取檔案

Resource resource=new ServletContextResource(req.getServletContext(),"file/cardKindModel.xlsx");
file = resource.getFile();

二: 匯入資料功能

頁面:

jquery.form.js 需要引入這個js

 $("#importExcel").ajaxSubmit({
                url:"/card/uploadeCountsExcel?id="+id,
                type:"post",
                timeout: 1000*60*60,
                success:function(data){
                    $('#uploadp').hide();
                    // $("#excel_file").val("");
                    // console.log($(data).text());
                    var res = JSON.parse($(data).text());
                    if(res.code=="0"){
                        $.messager.alert('tip',  '匯入成功');
                        $("#excel_file").val("");
                    }else if (res.code=="20001"){
                        $("#excel_file").val("");

                        $.messager.confirm('確認對話方塊', '匯入失敗,是否檢視詳情?', function(r){
                            if (r){
                                // window.location.href="/card/importError?id="+key; //跳轉到列表查詢頁
                                var iTop = (window.screen.availHeight - 30 - 750) / 2;
                                var iLeft = (window.screen.availWidth - 10 - 1200) / 2;
                                window.open("/card/importError?id="+key,"檢視詳情",'location=no,resizable=no,height=700,width=1200,innerWidth=1200,top='+iTop+',left='+iLeft);
                            }else{
                                // alert("否"); //清除快取
                            }
                        });

                    }else{
                        $.messager.alert('tip',  '匯入失敗,系統內部錯誤!');
                    }
                }
            });


java

@ResponseBody
    @RequestMapping(value ="/uploadeCountsExcel", method = {RequestMethod.POST})
    public JSONObject uploadeCountsExcel(@RequestParam(value="filename") MultipartFile file,@RequestParam(value="id") String id, HttpServletRequest req){
        JSONObject res = fileService.importExcel(file, id);
        RedisClient.getInstance().put("progress_" + id, 100, 60 * 60);
        return res;
    }

service

    @Override
    public JSONObject importExcel(MultipartFile file, String id) {
        importExcelLogger.info("【匯入次數】 importExcel -->執行開始。。。,請求ID=" + id);
        RedisClient.getInstance().put("progress_" + id, 1, 60 * 60);

        JSONObject res = new JSONObject();

        //執行校驗
        String checkRes = checkFile(file);
        if (checkRes != null) {
            res.put("code", 10001);
            res.put("msg", checkRes);
            return res;
        }
        RedisClient.getInstance().put("progress_" + id, 5, 60 * 60);

        //掃描資料
        JSONObject exeImportRes = exeImport(file.getOriginalFilename(), file);
        if(!"0".equals(exeImportRes.getString("code"))){
            res.put("code",exeImportRes.getString("code"));
            res.put("msg",exeImportRes.getString("msg"));
            return res;
        }
        List<String[]> exeImportData = ( List<String[]>)exeImportRes.get("data");
        RedisClient.getInstance().put("progress_" + id, 20, 60 * 60);

        //分析資料
        JSONObject applyDataRes = applyData(exeImportData,id);

        RedisClient.getInstance().put("progress_" + id, 100, 60 * 60);
        return applyDataRes;
    }

    @Override
    public JSONArray queryImportError(String id) {
        Object o = RedisClient.getInstance().get(id);
        if(o==null){
            return null;
        }
        JSONArray res= JSONArray.parseArray(o.toString());
        if(res.size()<2){
            return null;
        }

        res.remove(0);
        return res;
    }

    private String checkFile(MultipartFile file) {
        String msg = null;
        if (file == null) {
            msg = "上傳的檔案為空!";
            return msg;
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName == "") {
            msg = "檔名不能為空!";
            return msg;
        }
        Long size = file.getSize();
        if (size == 0) {
            msg = "檔案大小應該大於0!";
            return msg;
        }
        if(size>1024 * 1024){
            msg = "檔案大小應該不超過1MB!";
            return msg;
        }
        return msg;
    }

    private JSONObject exeImport(String name, MultipartFile file) {
        JSONObject res = new JSONObject();

        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        InputStream is = null;
        String extName = name.substring(name.lastIndexOf("."));
        try {
            is = file.getInputStream();
        } catch (IOException e) {
            importExcelLogger.error("【匯入次數】 importExcel.exeImport -->無法根據提交的檔案獲取輸入流!", e);
            res.put("code", "10002");
            res.put("msg", "檔案解析異常");
            return res;
        }

        try {
//            if (".xls".equals(extName)) {
//                wb = new HSSFWorkbook(is);
//            } else if (".xlsx".equals(extName)) {
//                wb = new XSSFWorkbook(is);
//            }
            if (".xlsx".equals(extName)) {
                wb = new XSSFWorkbook(is);
            }else{
                importExcelLogger.error("【匯入次數】 importExcel.exeImport -->副檔名無效,只支援xlsx型別檔案解析!");
                res.put("code", "10002");
                res.put("msg", "檔案解析異常");
                return res;
            }
        } catch (IOException e) {
            importExcelLogger.error("【匯入次數】 importExcel.exeImport -->無法根據輸入流得到Excel WorkBook!", e);
            res.put("code", "10002");
            res.put("msg", "檔案解析異常");
            return res;
        }

        if(wb==null){
            importExcelLogger.error("【匯入次數】 importExcel.exeImport -->Excel WorkBook未被初始化!");
            res.put("code", "10002");
            res.put("msg", "檔案解析異常");
            return res;
        }

        sheet = wb.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows();
        List<String[]> resList = new ArrayList<String[]>();
        for(int j=0;j<rows;j++){
            row = sheet.getRow(j);
//            int colNum = row.getPhysicalNumberOfCells();
            String[] rowContent = new String[8];
            for (int i = 0; i < 5; i++) {
                Cell cell = row.getCell(i);
                if("error".equals(getCellValueByCell(cell))){
                    importExcelLogger.error("【匯入次數】 importExcel.exeImport -->存在未知的Cell型別!,RowNum="+j);
                    res.put("code", "10002");
                    res.put("msg", "檔案解析異常");
                    return res;
                }
                rowContent[i]=getCellValueByCell(cell);
                if(i==2 && rowContent[i]!=null && !"".equals(rowContent[i]) && rowContent[i].indexOf(".")>-1){
                    String[] split = rowContent[i].split("[.]");
                    rowContent[i]=split[0];
                }
            }
            resList.add(rowContent);
        }

        res.put("code","0");
        res.put("data",resList);
        return res;
    }

    private  String getCellValueByCell(Cell cell){
        String cellVal="";
        if(cell==null||cell.toString().trim().equals("")){
            return cellVal;
        }else{
            switch (cell.getCellType()){
                case XSSFCell.CELL_TYPE_STRING:
                    cellVal=cell.getStringCellValue();
                    break;
                case XSSFCell.CELL_TYPE_NUMERIC:
                    cellVal=String.valueOf(cell.getNumericCellValue());
                    break;
                case XSSFCell.CELL_TYPE_BLANK:
                    cellVal="";
                    break;
                default:
                    cellVal="error";
                    break;
            }
            return cellVal;
        }
    }


分析資料是業務程式碼 就不上了。