Excel导入导出(ant design+spring boot)

时间:2024-05-20 13:03:59
1、运用ant design的upload组件,将Excel中的数据批量导入到数据库
upload组件的action往后台传递的是multipartfile类型,而使用jxl/poi方式读取文件要求文件类型为file,因此存在multipartfile转换file的过程。
转换方法为:将multipartfile转换为输入流(调用getInputStream()),然后直接读取;
Excel导入导出(ant design+spring boot)
Excel导入导出(ant design+spring boot)
2、在spring boot后台程序中通知浏览器下载文件
A. 下载spring boot的静态资源:静态资源在程序启动时被加载进去,如果中途资源被修改,就不能及时获取到最新的修改资源;唯一的解决方式是重新启动程序!
spring boot默认的静态资源映射:
/** 映射到 /static (或/public、/resources、/META-INF/resources)文件下;
优先级:META-INF/resources > resources > static > public 
访问方式:http://url:端口号/完整的文件名称(包括后缀)

举个例子:
项目目录结构如下图:
Excel导入导出(ant design+spring boot)
Excel导入导出(ant design+spring boot)
在浏览器地址栏中输入localhost:8080/10.xls来实现下载文件
B.将excel文件以流的方式输出到浏览器中
Excel导入导出(ant design+spring boot)
Excel导入导出(ant design+spring boot)
reponse请求头:
response.setContentType("application/x-download;charset=UTF-8");
response.setHeader("Content-Disposition",
"attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8"));
在浏览器中输入调用该方法的url可完成下载
3、导入导出需要的依赖
excel解析有两种方式:jxl和poi;它们的区别:jxl只能解析03版excel(后缀为.xls),而poi能解析03版excel和07版excel(后缀为.xlsx)
因为导入的excel版本未知,因此采用poi解析方式比较合适;
在这里引入与poi有关的依赖:
-----------------------------------------------------------
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
-----------------------------------------------------------
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
-----------------------------------------------------------
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
-----------------------------------------------------------
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>