改成这样:我测试成功了。<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body leftmargin="0" topmargin="0" bgcolor="#FFFFFF">
<%
response.reset();
String filename = "a.xls"; response.setContentType("application/vnd.ms-excel"); BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(request.getRealPath(filename)));
bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048];
int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
} } catch(final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
%>
</body>
</html>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body leftmargin="0" topmargin="0" bgcolor="#FFFFFF">
<%
response.reset();
String filename = "a.xls"; response.setContentType("application/vnd.ms-excel"); BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(request.getRealPath(filename)));
bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048];
int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
} } catch(final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
%>
</body>
</html>
//下载文件
response.reset();
response.setContentType("bin");
response.setHeader("Content-Disposition",
"attachment; filename=\"" + fileName +
//fileName 为文件名,可以为中文。
"\""); ServletOutputStream out = response.getOutputStream();
java.io.File ffile = new java.io.File(request.getRealPath(filePath1));
//filePath1 为 文件所在目录
if (!ffile.exists()) {
errMsg = URLEncoder.encode("系统找不到该文件!", "GBK");
linkStr = "/error/Error.jsp?errMsg=" + errMsg;
this.forward(linkStr, request, response);
return;
} InputStream inStream = new FileInputStream(ffile); //循环取出流中的数据
byte[] b = new byte[1024];
int len;
while ( (len = inStream.read(b)) > 0) {
out.write(b, 0, len);
}
out.close();
inStream.close();
}
catch (Exception ex) {
ex.printStackTrace();
this.exceptionError(request, response);
}