美文网首页
excel下载 前端:vue 后台:java

excel下载 前端:vue 后台:java

作者: 小酒窝_David | 来源:发表于2020-03-28 11:02 被阅读0次

    好久没写东西了,项目中要用到前端下载excel,我们的前端选择的是VUE,后端选择的是java,我就写一下实现吧,方便后来人少走一些弯路。
    java后台实现代码

      @ApiOperation(value = "导出日志",notes = "导出列表")
        @RequestMapping(value = "/exportLogs",method = RequestMethod.GET)
        @ResponseBody
        public ApiResult<?> exportExcel(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
            if (request ==null||response == null){
                return ApiResult.fail(ErrorCode.DATA_OP_EXCEPTION, "数据库操作异常!");
            }
            try {
                String startTime = request.getParameter("startLong");
                String endTime = request.getParameter("endLong");
                String serialNum = request.getParameter("serialNum");
                String type = request.getParameter("type");
                String operator = request.getParameter("operator");
                LogBean logBean = new LogBean();
                logBean.setPageNumber(1);
                logBean.setPageSize(Integer.MAX_VALUE);
                if (startTime != null && !startTime.equals("")) {
                    logBean.setStartTime(new Date(Long.valueOf(startTime)));
                }
                if (endTime != null && !endTime.equals("")) {
                    logBean.setEndTime(new Date(Long.valueOf(endTime)));
                }
                if (serialNum !=null&&!serialNum.equals("")){
                    logBean.setSerialNum(serialNum);
                }
                if (type !=null&&!type.equals("")){
                    logBean.setType(Integer.valueOf(type));
                }
                if (operator !=null&&!operator.equals("")){
                    logBean.setOperator(operator);
                }
                List<LogEntity> list = logService.getLogList(logBean);
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/x-download");
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
                String fileName = simpleDateFormat.format(date).toString()+".xls";
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment");
                response.addHeader("filename",fileName);
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet("sheet1");
                sheet.setColumnWidth(0, 4000);//设置列宽
                sheet.setColumnWidth(1,4000);
                sheet.setColumnWidth(2,4000);
                sheet.setColumnWidth(3,4000);
                sheet.setColumnWidth(4,4000);
                sheet.setColumnWidth(5,8000);
                sheet.setDefaultRowHeight((short) (2 * 256));//设置行高
                HSSFFont font = wb.createFont();
                font.setFontName("宋体");
                font.setFontHeightInPoints((short) 16);
                HSSFRow row = sheet.createRow(0);
                HSSFCell cell = row.createCell(0);
                cell.setCellValue("时间");
                cell = row.createCell(1);
                cell.setCellValue("操作人");
                cell = row.createCell(2);
                cell.setCellValue("业务类型");
                cell = row.createCell(3);
                cell.setCellValue("序列号");
                cell = row.createCell(4);
                cell.setCellValue("IP");
                cell = row.createCell(5);
                cell.setCellValue("操作内容");
               HSSFRow rows;
               HSSFCell cell1s;
                LogTypeEnum[] values = LogTypeEnum.values();
                Map<Integer, String> resultMap = new HashMap<Integer, String>();
                for (LogTypeEnum logTypeEnum : values) {
                    resultMap.put(logTypeEnum.getCode(), logTypeEnum.getMsg());
                }
               for (int i=0;i<list.size();i++){
                   LogEntity logEntity = list.get(i);
                   rows = sheet.createRow(i+1);
                   cell1s = rows.createCell(0);
                   cell1s.setCellValue(simpleDateFormat.format(logEntity.getTime()));
                   cell1s = rows.createCell(1);
                   cell1s.setCellValue(logEntity.getOperator());
                   cell1s = rows.createCell(2);
                   cell1s.setCellValue(resultMap.get(logEntity.getType()));
                   cell1s = rows.createCell(3);
                   String serialNumGet = logEntity.getSerialNum();
                   if (serialNumGet ==null||serialNumGet .equals("")){
                       serialNumGet = "---";
                   }
                   cell1s.setCellValue(serialNumGet);
                   cell1s = rows.createCell(4);
                   String ipGet = logEntity.getIp();
                   if (ipGet ==null||ipGet .equals("")){
                       ipGet = "---";
                   }
                   cell1s.setCellValue(ipGet);
                   cell1s = rows.createCell(5);
                   cell1s.setCellValue(logEntity.getContent());
               }
                try {
                    OutputStream out = response.getOutputStream();
                    wb.write(out);
                    out.close();
                    wb.cloneSheet(0);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return ApiResult.fail(ErrorCode.DATA_OP_EXCEPTION, "数据库操作异常!");
                }
            }catch (Exception e){
                LOGGER.error("getLogList exception", e);
                return ApiResult.fail(ErrorCode.DATA_OP_EXCEPTION, "数据库操作异常!");
            }
            return ApiResult.success();
        }
    

    前台代码实现

    async exportExcel() {
          let self = this;
          this.queryParam.startLong = this.timeRender(
            this.queryParam.startTimeTemp
          );
          this.queryParam.endLong = this.timeRender(this.queryParam.endTimeTemp);
          let downUrl = "exportLogs?" + $.param(self.queryParam);
          axios({
            method: "get",
            url: downUrl,
            responseType: "blob"
          }).then(data => {
            if (data && data.headers && data.headers.filename) {
              let url = window.URL.createObjectURL(data.data);
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              link.setAttribute("download", decodeURI(data.headers.filename));
              document.body.appendChild(link);
              link.click();
            } else {
              (this.$message || {}).warning('error');
            }
          });
        },
    

    相关文章

      网友评论

          本文标题:excel下载 前端:vue 后台:java

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