ajax 是無(wú)法直接導(dǎo)出excel的,因?yàn)閍jax返回值只能是字符流,而導(dǎo)出excel是后臺(tái)往瀏覽器中寫入二進(jìn)制的字節(jié)流
- 瀏覽器彈窗下載excel文件
//response設(shè)置頭文件
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//導(dǎo)出excel其實(shí)就是后臺(tái)給瀏覽器寫入字節(jié)流
Workbook excel = new XSSFWorkbook();
....省略寫入數(shù)據(jù)代碼
excel.write(outputStream);
outputStream.flush();
outputStream.close();
導(dǎo)出excel方法:
- 方法一:window.open() & form表單.submit().
- 方法二:ajax請(qǐng)求把參數(shù)緩存在后端返回給前端key,前端ajax再次發(fā)起一個(gè)window.open(url?key=key)即可,詳細(xì)代碼如下:
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無(wú)法直接導(dǎo)出excel,所以第一次把請(qǐng)求生成的ExcelParam緩存起來(lái),然后前端再次window.open(url);
*/
public static Map<String, ExcelParam> excelParamCache = new ConcurrentHashMap<>();
//第一步緩存參數(shù)
@SuppressWarnings("unchecked")
@RequestMapping(value = "/export")
@ResponseBody
public R export(@RequestBody ExcelParam excelParam) {
Assert.notNull(excelParam,"參數(shù)不能為空");
Assert.notNull(excelParam.getUrl(),"url參數(shù)不能為空");
Assert.notNull(excelParam.getColumns(),"columns參數(shù)不能為空");
Assert.notNull(excelParam.getFileName(),"fileName參數(shù)不能為空");
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);
}
}