excel下载 前端:vue 后台:java

excel下载 前端:vue 后台:java

以下代码片段来自别人,亲测可用,我这里做笔记用,用来记录前台请求方式改为post,后台返回字节流变成乱码的问题。以下源代码片段get请求可直接拿来即用。

@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');
        }
      });
    },

贴几个地址:https://www.jianshu.com/p/816d87d85e6a
https://blog.csdn.net/qq_34940644/article/details/90643319

以下是我的修改部分:

@RequestMapping(value = "/exportExcel",method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public void exportExcel(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String, Object> map){}
async exportExcel() {
            let vm = this;
            let queryParam = {};
            queryParam.chartDatas = vm.indexChartData.chartDatas;
            queryParam.title = vm.chartConfig1.title.text;
            vm.$http({
                method: "post",
                url: vm.$serverPath.exportExcel,
                data: queryParam,
                contentType: "application/json;charset=utf-8",
                responseType: 'blob',
                dataType: 'json',
            }).then(data => {
                if (data && data.headers && data.headers.filename) {
                    var reader = new FileReader();
                    reader.readAsDataURL(data.data);
                    reader.onload = function (e) {
                        var a = document.createElement('a');
                        a.download = 'data.xls';
                        a.href = e.target.result;
                        $('body').append(a);
                        a.click();
                        $(a).remove();
                    }
                } else {
                    (this.$message || {}).warning('error');
                }
            });
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值