我可以使用apache poi创建excel文件,但是如何让用户下载将在服务器上创建的excel文件?
public String export(UserDetails user) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
List<UserDetails> lstUserDetail = getUserDetailList();
for (short RowNum=1; RowNum<lstUserDetail.size();RowNum++){
HSSFRow row = sheet.createRow(RowNum);
UserDetails userDetail = lstUserDetail.get(RowNum);
HSSFCell cell1 = row.createCell((short)0);
HSSFCell cell2 = row.createCell((short)1);
HSSFCell cell3 = row.createCell((short)2);
HSSFCell cell4 = row.createCell((short)3);
cell2.setCellValue(userDetail.getStrUserName());
cell3.setCellValue(userDetail.getStrEMail());
cell4.setCellValue(userDetail.getStrUserPhone());
cell5.setCellValue(userDetail.getStrUserAddress());
}
FileOutputStream fileOut = new FileOutputStream("E:\\workbook.xls");
wb.write(fileOut);
fileOut.close();
return null;
}
答案 0 :(得分:0)
尝试下面,一旦用户点击下载链接
,您将调用FileDownload servletpublic class FileDownload extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
String filename = "E:\\workbook.xls";
ServletOutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(filename);
response.setContentType("application/vnd.ms-excel");
response.addHeader("content-disposition",
"attachment; filename=" + filename);
int octet;
while((octet = in.read()) != -1)
out.write(octet);
in.close();
out.close();
}
}