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);
}
}