jsp实现导出word文件代码

<%@ page pageEncoding="gb2312"%>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<%

String filename = new String(request.getParameter("reportname").getBytes("iso8859-1"),"gb2312");
response.setHeader("Content-disposition","attachment; filename="+java.net.URLEncoder.encode(filename,"UTF-8")+".doc");
response.setContentType("application/msword");

BufferedInputStream bis = null;
OutputStream bos = null;
try {
	System.out.println(getServletContext().getRealPath("/")+"word\\" + filename+".doc");
    bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("/")+"word\\" + filename+".doc"));
    bos = response.getOutputStream();

    byte[] buff = new byte[2048];
    int bytesRead;

    while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        bos.write(buff,0,bytesRead);
    }
    bos.flush();

} catch(final IOException e) {
    System.out.println ( "出现IOException." + e );
} finally {
    if (bis != null)
        bis.close();
    if (bos != null)
        bos.close();
}
out.clear();
out = pageContext.pushBody();
%>
<script type="text/javascript">

function closeit(){
	setTimeout("self.close()",2000) //毫秒
}

</script>
<body onload="closeit()">文件导出中...
</body>

</html>

你可能感兴趣的:(jsp)