生成excel并发送给客户端
首先需要将excel写入输出流中,这个代码有机会给补充。这篇展示的是写入流之后,发送给客户端的代码示例:
1 /** 2 * 将生成的excel发送给客户端 3 * @param response 4 * @param os 输出流 5 * @param fileName excel文件名称 6 */ 7 public static void sendExcel(HttpServletResponse response , ByteArrayOutputStream os, String fileName){ 8 byte[] content = os.toByteArray(); 9 InputStream is = new ByteArrayInputStream(content); 10 // 设置response参数,可以打开下载页面 11 BufferedInputStream bis = null; 12 BufferedOutputStream bos = null; 13 try { 14 15 String downLoadName = new String((fileName+".xls").getBytes("gbk"), "iso8859-1"); 16 response.reset(); 17 response.setContentType("applicationnd.ms-excel;charset=utf-8"); 18 response.setHeader("Content-Disposition", "attachment;filename="+ downLoadName); 19 ServletOutputStream out = response.getOutputStream(); 20 bis = new BufferedInputStream(is); 21 bos = new BufferedOutputStream(out); 22 byte[] buff = new byte[2048]; 23 int bytesRead; 24 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 25 bos.write(buff, 0, bytesRead); 26 } 27 } catch (final IOException e) { 28 e.printStackTrace(); 29 } finally { 30 if (bis != null) 31 try { 32 bis.close(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 if (bos != null) 37 try { 38 bos.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 }
这样既可让客户端接收到excel并下载。