@RequestMapping("/downLoadFailRecord") public ModelAndView downLoadFailRecord( HttpServletRequest request,HttpServletResponse response, @ModelAttribute("filePath")String filePath) throws Exception{ log.info("======文件路径====filePath:"+filePath); String excelData = ""; String str = "医路通保存失败统计记录"; excelData = medicalService.getFailMedical(filePath); log.info("*******解析的字符串为:"+excelData); response.setContentType("application/ms-txt;charset=UTF-8"); response.addHeader("Content-Disposition","attachment; filename=" + new String(str.getBytes("GBK"),"ISO8859_1") + ".xls"); response.getWriter().write(excelData); return null; }
excelData为object类型的数据字符串
方法二:发现的有点晚,还好不算太晚
@RequestMapping(value="downLoadFile") public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception { //方法二:非常好用的下载文件代码 String outFileName = "测试文件.xls"; String filePath="d:/batchInsure.xls"; /*String outFileName = "测试文件.csv"; String filePath="d:/secendTest.csv";*/ BufferedInputStream bis = null; BufferedOutputStream bos = null; ServletOutputStream out = null; PrintWriter pw = null; FileInputStream fis = null; fis = new FileInputStream(filePath); response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(outFileName,"UTF-8")); out = response.getOutputStream(); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int len = 0; while((len=bis.read(buff))!=-1){ bos.write(buff,0,len); } bos.flush(); out.flush(); }
方法二非常好用,适合各种类型的文件