JSP download Excel file Implementation method Many, today also encountered this problem, disorderly knock a burst, finally fix, write down to share with friends.
Assume that the JSP page that needs to download the Excel file is named: down.jsp
The corresponding background action name is: Downexcel.java (implemented with struts, similar to other frameworks)
Add Downaction method in Downexcel.java, implement the download step
Public Actionforward downaction (actionmapping mapping, Actionform form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
Java.io.OutputStream o = Response.getoutputstream ();
byte b[] = new byte[500];
Java.io.File fileload = new Java.io.File (Request.getrealpath ("/web-inf/" + "/f.xls");
System.out.println (Fileload.getpath ());
Response.reset ();
Response.setcontenttype ("application/vnd.ms-excel");
Response.setheader ("Content-disposition",
"Attachment; Filename=text.xls ");
Long filelength = Fileload.length ();
String length1 = string.valueof (filelength);
Response.setheader ("Content_length", length1);
Java.io.FileInputStream in = new Java.io.FileInputStream (fileload);
int n;
while ((n = in.read (b))! =-1) {
O.write (b, 0, N);
}
In.close ();
O.close ();
return null;
}
The blue part is the path to the Excel file you want to download, and notice that the change is possible.
Then there is the JSP page section:
Put a ' download ' button in the down.jsp:
<input type= "button" value= "Download Template" class= "BT2" onclick= "Down ();"/>
There is also a script:
function down () {
var action = "<%=request.getcontextpath ()%>/downexcel.do?method=downaction";
Window.location=action;
}
Ok! It's done, why do you put the implementation of the download in the background? Originally I was to put this part on another page (anthor.jsp), but this download after anthor.jsp close, even in the onload write Window.close (), but also no, time haste I did not think other ways to solve, left to the conscientious, Oh, Mo forgot to tell me, O (∩_∩) o~
In addition, see the realization of a brother is such, the highlight in the last two sentences, I think there is if the page to implement the download step, should not out of the brother said, as follows:
<%
Java.io.OutputStream o = Response.getoutputstream ();
byte b[] = new byte[500];
Java.io.File fileload = new Java.io.File (Request.getrealpath ("/web-inf/" + "/f.xls");
System.out.println (Fileload.getpath ());
Response.reset ();
Response.setcontenttype ("application/vnd.ms-excel");
response.setheader ("Content-disposition",
"attachment; Filename=text.xls ");
long filelength = Fileload.length ();
String length1 = string.valueof (filelength);
response.setheader ("Content_length", length1);
java.io.FileInputStream in = new Java.io.FileInputStream (fileload);
int n;
while ((n = in.read (b))! =-1) {
O.write (b, 0, N);
}
In.close ();
Out.clear ();
out = Pagecontext.pushbody ();
%>
JSP download Excel file