ajax请求url导出excel,ajax导出excel

ajax 是无法直接导出excel的,因为ajax返回值只能是字符流,而导出excel是后台往浏览器中写入二进制的字节流

浏览器弹窗下载excel文件

//response设置头文件

response.setContentType("application/vnd.ms-excel");

response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

//导出excel其实就是后台给浏览器写入字节流

Workbook excel = new XSSFWorkbook();

....省略写入数据代码

excel.write(outputStream);

outputStream.flush();

outputStream.close();

导出excel方法:

方法一:window.open() & form表单.submit().

方法二:ajax请求把参数缓存在后端返回给前端key,前端ajax再次发起一个window.open(url?key=key)即可,详细代码如下:

JS代码

$.ajax({

url: '../../eldercare/excel/export?_' + $.now(),

type: 'post',

dataType: "json",

contentType : 'application/json',

data : JSON.stringify(this.tableOpts),

success: function(data){

window.open('../../eldercare/excel/downFromCache?key='+data.rows, '_self');

},

java代码

/**

* 由于ajax无法直接导出excel,所以第一次把请求生成的ExcelParam缓存起来,然后前端再次window.open(url);

*/

public static Map excelParamCache = new ConcurrentHashMap<>();

//第一步缓存参数

@SuppressWarnings("unchecked")

@RequestMapping(value = "/export")

@ResponseBody

public R export(@RequestBody ExcelParam excelParam) {

Assert.notNull(excelParam,"参数不能为空");

Assert.notNull(excelParam.getUrl(),"url参数不能为空");

Assert.notNull(excelParam.getColumns(),"columns参数不能为空");

Assert.notNull(excelParam.getFileName(),"fileName参数不能为空");

String key = UUID.randomUUID().toString();

excelParamCache.put(key,excelParam);

return CommonUtils.msg(key);

}

//第二步下载文件

@RequestMapping(value = "/downFromCache", method = RequestMethod.GET)

public void downFromCache(String key,HttpServletRequest request, HttpServletResponse response) {

try {

Assert.hasText(key,"key不能为空");

ExcelParam excelParam = excelParamCache.get(key);

excelService.reflexList(excelParam);

excelService.export(excelParam,request,response);

} catch (Exception e) {

e.printStackTrace();

excelParamCache.remove(key);

} finally {

excelParamCache.remove(key);

}

}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值