当前位置: 首页 > news >正文

springboot 下载 Excel 文件的 Controller 层案例

环境 pom.xml 中 springboot版本:

    <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.15</version></parent>

Excel 文件依赖:


<!-- POI --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency>

demo1

    // 下载 Excel@GetMapping(value = "/downloadData")public ResponseEntity<byte[]> downloadData2(@RequestParam("id") String id) throws IOException {log.info("---------------downloadData start-------------");String rootDirectory = request.getServletContext().getRealPath("/");log.info("rootDirectory:"+rootDirectory);// 临时放置文件目录Path p = Paths.get(rootDirectory, "temp");if (!p.toFile().exists()) {p.toFile().mkdirs();}log.info("---------------downloadData start 2 Render.... -------------");// 写 业务逻辑,生成 Excel FileFile file = null; log.info("###------------the excel file address:"+file.getAbsolutePath());// 下载成功返回二进制流return getResponseEntity(file,null,false);}private static ResponseEntity<byte[]> getResponseEntity(File file,String userAgent,boolean inline) throws IOException {ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();bodyBuilder.contentLength(file.length());// 二进制数据流
//        bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM);// 文件名编码String encodeFileName = URLEncoder.encode(file.getName(), "UTF-8");// IEif (userAgent!=null&&userAgent.indexOf("MSIE") > 0) {bodyBuilder.header("Content-Disposition", "attachment;filename=" + encodeFileName);} else { // 其他浏览器if (inline) {// 在浏览器中直接打开URL url = new URL("file:///" + file);bodyBuilder.header("Content-Type", url.openConnection().getContentType());bodyBuilder.header("Content-Disposition", "inline;filename*=" + encodeFileName);} else {// 直接下载bodyBuilder.header("Content-Disposition", "attachment;filename*=" + encodeFileName);bodyBuilder.header("Content-Type","application/vnd.ms-excel;charset=utf8");}}// 下载成功返回二进制流return bodyBuilder.body(Files.readAllBytes(file.toPath()));}

demo2

    @GetMapping(value = "/download2")public void download2(@RequestParam("id") String id,@RequestParam(required = false, defaultValue = "false") @ApiParam("参数 inline表示是否要在线浏览,true是,false否(默认).") boolean inline,@RequestHeader("user-agent") @ApiParam("参数userAgent 是为了兼容IE判断,如果使用谷歌,火狐浏览器就可以省略这个参数.") String userAgent,ServletRequest request,HttpServletResponse response) throws IOException {String rootDirectory = request.getServletContext().getRealPath("/");
//        System.out.println("rootDirectory:"+rootDirectory);// 临时放置文件目录Path p = Paths.get(rootDirectory, "temp");if (!p.toFile().exists()) {p.toFile().mkdirs();}// 根据业务生成 文件File file = new File("");this.download(response,file,null);}private void download(HttpServletResponse response, File file, String fileName){if(fileName==null){fileName = file.getName();}try(FileInputStream is = new FileInputStream(file);OutputStream os = response.getOutputStream()) {//通用的mime类型response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));byte[] buf = new byte[1024];int len = 0;while((len = is.read(buf))!=-1){os.write(buf,0,len);}}catch (Exception e) {throw new RuntimeException(e);}}

http://www.lryc.cn/news/312771.html

相关文章:

  • RabbitMQ队列
  • Day12:信息打点-Web应用源码泄漏开源闭源指纹识别GITSVNDS备份
  • 使用正确的技术和项目管理工具来定义项目范围
  • 【C++】类型转换和IO流
  • leetCode刷题 5.最长回文子串
  • 计算机组成原理面试题
  • 「Mybatis深入三」:高级查询-模糊查询
  • LabVIEW管道缺陷智能检测系统
  • java在cmd中乱码的问题解决
  • OpenHarmony教程指南—ArkUI中组件、通用、动画、全局方法的集合
  • 第二证券|金价逼近历史高点 黄金股价值有望重估
  • 关于51单片机晶振定时问题
  • NoSQL--2.MongoDB配置(Windows版)
  • HTML静态网页成品作业(HTML+CSS)——安徽宣笔设计制作(5个页面)
  • MySQL CTEs通用表表达式:进阶学习-递归查询
  • [Java安全入门]二.序列化与反序列化
  • Dutree:Linux 文件系统磁盘使用追踪工具
  • http和https的区别是什么?
  • 学习Android的第十九天
  • C#上位机调试经验
  • BUUCTF---[极客大挑战 2019]BabySQL1
  • 0基础跨考计算机|408保姆级全年计划
  • C# 操作LiteDB
  • LeetCode 2917.找出数组中的 K-or 值:基础位运算
  • MySQL窗口函数:从理论到实践
  • Vue+SpringBoot打造考研专业课程管理系统
  • python基础第二天
  • YOLOV9论文解读
  • 【Spring】21 通过@Primary注解优化注解驱动的自动装配
  • 【HTML】HTML基础7.3(自定义列表)