springboot下载excel文件
1.最近在项目中需要下载excel文件,直接下载打开会提示文件不可用或者文件已损害,利用poi可解决这个问题,步骤如下:(1)通过httpServletRequest获取操作系统:String osp = request.getHeader("User-Agent");String os = "Linux";if (osp.indexOf("Windows") != -1){os = "Windo
·
1.最近在项目中需要下载excel文件,直接下载打开会提示文件不可用或者文件已损害,利用poi可解决这个问题,步骤如下:
(1)通过httpServletRequest获取操作系统: String osp = request.getHeader("User-Agent"); String os = "Linux"; if (osp.indexOf("Windows") != -1){ os = "Windows"; }
(2)根据自己系统的查询方式得到文件路径
String path = staffTemplate.getSaveUrl() + staffTemplate.getServerName();
(3)设置下载文件名称,需要加excel后缀,其中sub根据系统文件名确定
if (os.equals("Windows")){ name = new String(name.getBytes("UTF-8"),"ISO-8859-1"); response.addHeader("Content-Disposition", "attachment; filename="+name+sub); }else { response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(name, "UTF-8")+sub); }
(4)利用poi实现excel的输出
//创建缓冲输入流 BufferedInputStream bis = null; OutputStream outputStream = null; try { outputStream = response.getOutputStream(); byte[] buff = new byte[1024]; //这个路径为待下载文件的路径 bis = new BufferedInputStream(new FileInputStream(new File(path))); Workbook workbook = null; //判断版本 if (".xlsx".equals(sub)) { workbook = new XSSFWorkbook(bis); }else { workbook = new HSSFWorkbook(bis); } workbook.write(outputStream); outputStream.flush(); } catch ( IOException e ) { e.printStackTrace(); return error("网络错误,请重试!"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
更多推荐
已为社区贡献1条内容
所有评论(0)