我已经使用servlet在eclipse中使用JXL jar文件创建了一个excel文件,现在我想下载它,但无法这样做



我在excel的JSP文件下载中使用了一个按钮。我已经从oracle数据库导入数据到excel文件,当我点击下载按钮时,它生成excel,但我希望它从客户端下载。

jsp code..
<body>
<form method="get" action="ViewEmployee">
<input type="submit" name="viewall" value="View All Employees">
</form>
<br>
<form method="get" action="ViewEmployee">
<input type="submit" name="create_xls" value="View in Excel format" onClick="window.location.href='/path/to/excel/EmployeeData.xls'">
</form>
</body>

只需重定向到已生成文件的URL,并确保它作为URL可见

您必须将文件作为字节数组读取,并将其写入setvlet响应的输出流,如下所示。

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/vnd.ms-excel");
        res.setHeader("Content-Disposition","attachment;filename=file.xls");
        File file = new File("/path/to/excel/EmployeeData.xls");
        FileInputStream fileIn = new FileInputStream(file);
        ServletOutputStream out = res.getOutputStream();
        byte[] outputByte = new byte[4096];
        int byteRead;
        while( (byteRead = fileIn.read(outputByte)) != -1){
           out.write(outputByte, 0, byteRead);
        }
        fileIn.close();
        out.flush();
        out.close();
}

最新更新