编程语言
首页 > 编程语言> > Java对Excel表格的读取,处理,下载

Java对Excel表格的读取,处理,下载

作者:互联网

Excel的下载:

  直接通过流来读取路径下的Excel文件,将输入流(InputStream)转为字节输出流(OutputStream)后,放入HttpResponse中就OK了,前提是要设置好响应头和文件类型编码等设置

具体代码如下:

 @GetMapping(/download)
 public void downloadExcel(HttpServletResponse response){
 try{
String fileName = "xxx.xls"
  InputStream docfile = getClass().getClassLoader().getResourceAsStream(fileName);
  //设置响应的各种信息
  response.setCharacterEncoding("UTF-8");
  response.setHeader("content-type","applaction/octet-stream;charset=UTF-8");
  response.setContentType("application/octet-stream;charset=UTF-8");
  response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(fileName));
  //把输出流存入response
  ServletOutputStream outStream = response.getOutputStream();
  //把文件写入outputstream 固定操作
  byte[] buffer = new byte[10 * 1024];
  int n = 0;
  while((n = docfile.read(buffer)) != -1){
  outStream.write(buffer,0,n);
}
  outStream.flush();
  outStream.close();
  docfile.close();
}catch(Exception e){
e.pringtStackTrace();
}
}

 

标签:Java,读取,Excel,outStream,fileName,UTF,docfile,response
来源: https://www.cnblogs.com/wenyuan-demo/p/14484945.html