Today did Excel export download, tossing a day to discover Ajax datatype There is no flow type, which means that you can not use Ajax to accept the output stream from the background. But you can use a dynamically created form instead.
Here are some of the source code for Project practice:
1, the background controller layer (Hssfworkbook Create Excel Process I wrote in the service layer, here is not pasted out):
1 //Export Excel2@RequestMapping (value= "/outputexcel", method=requestmethod.post)3 Public@ResponseBodyvoidOutputexcel (Hssfworkbook workbook,httpservletrequest request,httpservletresponse response)throwsioexception{4 //Get Parameters5String nd=request.getparameter ("nd");6String co_code=request.getparameter ("Co_code");7 //Excel Download Settings8OutputStream out=Response.getoutputstream ();9Response.setheader ("Content-type", "application/vnd.ms-excel");TenResponse.AddHeader ("Content-disposition", "Attachment;filename=mydata.xls"); OneResponse.setcontenttype ("Application/octet-stream"); AResponse.setcharacterencoding ("UTF-8"); -workbook=outputexcelservice.outputexcel (ND, co_code); - Try{ the //Return Data stream - Workbook.write (out); - Out.flush (); - out.close (); +}finally{ - Out.flush (); + out.close (); A } at}
2, the front-end JS source code (need to pay attention to 18 lines, the value of the action before adding a '. ', otherwise it may be 404):
1 //get the selection path and export the Excel2Viewmodel.saveexcel=function(){3 varCo_code= ""; 4 varnd=$ ("#select_nd_info"). Val ();//Select year5 varDw_value = $ ("#select_dw_info"). Val ();6 varinfo=ViewModel.ipCompDataTable.getSimpleData ();7 for(vari=0;i<info.length;i++){8 if(dw_value===info[i].co_name) {9Co_code=Info[i].co_code; Ten Break; One } A } - //define a form because Ajax cannot accept stream type data - varForm = $ ("<form>"); theForm.attr (' style ', ' Display:none '); -Form.attr (' Target ', '); -Form.attr (' method ', ' post '); -Form.attr (' Action ', './data_status/outputexcel ')); + - varINPUT1 = $ (' <input> ')); +Input1.attr (' Trpe ', ' hidden '); AInput1.attr (' name ', ' nd '); atInput1.attr (' value ', ND); - - varInput2 = $ (' <input> ')); -Input2.attr (' Trpe ', ' hidden '); -Input2.attr (' name ', ' Co_code '); -Input2.attr (' value ', Co_code); in //Place the form in the body -$ (' body '). append (form); to form.append (INPUT1); + form.append (INPUT2); - form.submit (); the Form.remove (); *}
3, run the project, ok!
Hope to help you!
Hssfworkbook + form + HttpServletResponse for Excel downloads