vue实现excel文件导出,Java后端文件流输出

  • vue代码
    • 添加request请求拦截
downloadService.interceptors.response.use(
    response => {
      // 导出
      const headers = response.headers
      if(headers['content-type'] === 'application/vnd.ms-excel;charset=UTF-8'){
        return response.data
      }
    },
    error => {
      return Promise.reject(error)
    }
)	
  • vue下载代码实现, axios调用接口请求数据后返回response
export function download(data, name) {
    
    const content = data
    const blob = new Blob([content])
    const fileName = name
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
}
  • Java后台代码实现
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
		    response.setHeader("Content-Disposition", "attachment;filename="+
		            java.net.URLEncoder.encode(fileName,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
		    //e.printStackTrace();
		    return AitgResponse.err(AitgResponse.CODE_ERROR, e.getMessage());
		}
		  try(IExcelWriter excelWriter = ExcelUtil.getBigExcelWriter();
			// OutputStream outputStream = new FileOutputStream(fileName)
					 OutputStream os = response.getOutputStream();) {
	        // 可根据实际需要,多次写入列表
	        excelWriter.write(list);
	        // 将列表内容真正的输出到 excel 文件
	        excelWriter.flush(os);
	    } catch (IOException e) {
	        throw new ExcelRuntimeException(e);
	    }
Logo

前往低代码交流专区

更多推荐