使用ExcelUtil快速实现对文件的导入导出系列。
1、pom文件
<dependency> <groupId>net.oschina.likaixuan</groupId> <artifactId>excelutil</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2、实体类
@Data @NoArgsConstructor @AllArgsConstructor public class Student { @Excel(title = "姓名") private String name; @Excel(title = "学号") private String stu_no; @Excel(title = "年龄") private int age; }
3、controller接口
@RestController public class ExcelController { /** * @Author:MuJiuTian * @Date:2019/11/9 下午3:14 * @Description:excel导入数据 */ @PostMapping(value = "/importFile") public void importFile(MultipartFile file) throws Exception { // 1、读取文件列表内容 List<Student> students = ExcelUtil.readXls(file.getBytes(),Student.class); // 2、处理业务逻辑,最后存储数据库操作,此步骤忽略,只讲ExcelUitl用法 // 3、输出,打印到控制台 students.stream().forEach(System.out::println); } /** * @Author:MuJiuTian * @Date:2019/11/9 下午3:14 * @Description:数据导出到excel */ @GetMapping(value = "/exportFile") public void exportFile(HttpServletResponse response) throws Exception { // 1、根据条件将需要导出数据查找出来 studentService.selectAll();这里不做处理 List<Student> students = Arrays.asList( new Student("小汤","2013245060501",20), new Student("王轩","2013245060502",21), new Student("紫玉","2013245060503",18) ); // 2、导出到具体路径(如d盘或者mac桌面) ExcelUtil.exportExcel("",students,Student.class); // 3、导出到浏览器(正常情况下我们使用浏览器下载) ExcelUtil.exportExcelOutputStream(response,students,Student.class); } // 测试 导入 @PostMapping(value = "/test_import") public void test_import() throws Exception { List<Student> students = ExcelUtil.readXls("/Users/tentsuuhou/Desktop/excelutil.xlsx",Student.class); students.stream().forEach(System.out::println); } // 测试 导出 @GetMapping(value = "/test_export") public void test_export(HttpServletResponse response) throws Exception { List<Student> students = Arrays.asList( new Student("小汤","2013245060501",20), new Student("王轩","2013245060502",21), new Student("紫玉","2013245060503",18) ); ExcelUtil.exportExcelOutputStream(response,students,Student.class); } }
4、测试导入
测试导入接口,准备文件如图:
执行接口:
http://localhost:8081/test_import
结果如下:
5、测试导出
执行接口:
http://localhost:8081/test_export
结果:
成功!
来源:oschina
链接:https://my.oschina.net/u/3209213/blog/3127824