springmvc框架中实现网页下载功能(以导出excel为例)
java后台做法如下:
public void downLoad(HttpServletRequest request,HttpServletResponse response,HttpSession sesssion){
List<Map<String,Object>> list=selectData()
;//到数据库中查询需要导出的信息
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("导出信息");//excel sheet标题
HSSFRow row = sheet.createRow((int) 0);//创建导出的行数(以0开始)
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell((short) 0);//创建第一列
cell.setCellValue("数据1");//第一列列名
cell.setCellStyle(style);//第一列样式(居中) cell = row.createCell((short) 1);//创建第二列 cell.setCellValue("数据2");//第二列列名
cell.setCellStyle(style);//第二列样式(居中)
for(int i=0;i<list.size();i++){ //给列赋值
row = sheet.createRow( i + 1);//循环创建 Map<String,Object> map1=list.get(i); row.createCell((short) 0).setCellValue(map1.get(0).toString());//给列赋值 row.createCell((short) 1).setCellValue(map1.get(1).toString()); }
try{
FileOutputStream out=new FileOutputStream("下载路径");
wb.write(out); out.close();
load(request,response,session);//网页下载
}catch(Exception e){e.printStackTrace}
}
public void load(HttpServletRequest request,HttpServletResponse response,HttpSession sesssion){
OutputStream outputStream = null; InputStream inputStream = null; String rootPath=""; try { response.setCharacterEncoding("utf-8"); //设置文件MIME类型 response.setContentType("application/octet-stream"); //设置Content-Disposition response.setHeader("Content-Disposition", "attachment;filename=" + new String("导出数据.xls".getBytes("gb2312"), "iso-8859-1")); rootPath = "上面下载路径"; inputStream = new FileInputStream(rootPath); outputStream = response.getOutputStream(); //写文件 int b; while ((b = inputStream.read()) != -1) { outputStream.write(b); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } if (outputStream != null)//删除原有下载文件 try { outputStream.close(); File file=new File(rootPath); if(file.exists()){ file.delete(); } } catch (IOException e) { e.printStackTrace(); } }