今天做了excel的导出下载,折腾了一天才发现ajax的dataType里面没有流类型,这就意味着不能用ajax来接受后台传来的输出流。但是可以用动态创建的form来代替。
下面是项目实践的部分源码:
1、后台Controller层(HSSFWorkbook创建excel的过程我写在了Service层,这里就不粘贴出来了):
1 //导出excel 2 @RequestMapping(value="/outPutExcel",method=RequestMethod.POST) 3 public @ResponseBody void outPutExcel(HSSFWorkbook workbook,HttpServletRequest request,HttpServletResponse response) throws IOException{ 4 //获取参数 5 String nd=request.getParameter("nd"); 6 String co_code=request.getParameter("co_code"); 7 //excel下载设置 8 OutputStream out=response.getOutputStream(); 9 response.setHeader("Content-Type","application/vnd.ms-excel"); 10 response.addHeader("Content-Disposition","attachment;filename=mydata.xls"); 11 response.setContentType("application/octet-stream"); 12 response.setCharacterEncoding("UTF-8"); 13 workbook=outPutExcelService.outPutExcel(nd, co_code); 14 try{ 15 //返回数据流 16 workbook.write(out); 17 out.flush(); 18 out.close(); 19 }finally{ 20 out.flush(); 21 out.close(); 22 } 23 }
2、前端js源码(需要注意18行,action的值前加了一个‘.‘ ,不然可能会404 ):
1 //获取选择路径,并导出excel 2 viewModel.saveExcel=function(){ 3 var co_code=""; 4 var nd=$("#select_nd_info").val(); //选择年度 5 var dw_value = $("#select_dw_info").val(); 6 var info=viewModel.ipCompDataTable.getSimpleData(); 7 for(var i=0;i<info.length;i++){ 8 if(dw_value===info[i].co_name){ 9 co_code=info[i].co_code; 10 break; 11 } 12 } 13 //定义form,因为ajax不能接受 流类型数据 14 var form = $("<form>"); 15 form.attr(‘style‘,‘display:none‘); 16 form.attr(‘target‘,‘‘); 17 form.attr(‘method‘, ‘post‘); 18 form.attr(‘action‘, ‘./data_status/outPutExcel‘); 19 20 var input1 = $(‘<input>‘); 21 input1.attr(‘trpe‘,‘hidden‘); 22 input1.attr(‘name‘, ‘nd‘); 23 input1.attr(‘value‘, nd); 24 25 var input2 = $(‘<input>‘); 26 input2.attr(‘trpe‘,‘hidden‘); 27 input2.attr(‘name‘, ‘co_code‘); 28 input2.attr(‘value‘, co_code); 29 //将表单放到body中 30 $(‘body‘).append(form); 31 form.append(input1); 32 form.append(input2); 33 form.submit(); 34 form.remove(); 35 }
3、运行项目,ok!
希望对你有帮助!
时间: 2024-10-06 13:55:30