1、从文件系统下载到浏览器
/** * 下载 * @param res * @param fileName */ @RequestMapping(value = "/download", method = RequestMethod.GET) public void fileDownload(HttpServletResponse res,String fileName) { //设置相应类型为文件 res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); //每次读取一个1K byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { //读文件流 bis = new BufferedInputStream(new FileInputStream(new File(filePath + fileName))); //浏览器输出流(下载到浏览器) os = res.getOutputStream(); //读写操作 int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2、使用freemarker从程序下载Exce到l浏览器
/**
* 下载
* @param response
*/
@RequestMapping(value = "/export") public void export(HttpServletResponse response){ try { //设置导出Excel String fileName = "报表_"+dateFormat.format(new Date())+".xls"; response.setHeader("Content-Disposition", String.format("attachment; filename="%s"", URLEncoder.encode(fileName, "utf-8"))); response.setContentType("application/vnd.ms-excel;charset=gb2312"); //加载Excel模板 Configuration config = new Configuration(Configuration.VERSION_2_3_29); config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_29)); config.setDirectoryForTemplateLoading(new File(exportTemplateLoadPath)); //加载模板 Template template = config.getTemplate("test.xml"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8); //封装数据 List<SubData> subDatas = new ArrayList<SubData>(); subDatas.add(new SubData("1","测试1","软件",1,"套",200,200,"网络")); subDatas.add(new SubData("2","测试2","硬件",1,"件",100,100,"试验")); subDatas.add(new SubData("3","测试3","书籍",1,"本",100,100,"教育")); Data data = new Data("2020年12月8日","100100","张三","男","15559623236","sp.qin@qq.com",30); data.setSubDatas(subDatas); //构建Map Map<String, Data> map = new HashMap<String, Data>(); map.put("data",data); template.process(map,outputStreamWriter); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } }