1.创建SpringBoot项目,导入依赖
<parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.7.6</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.3</version> </dependency> </dependencies>View Code
2.创建一个所需实体类,例如User
@TableName("user") @Data public class User implements Serializable { @ExcelProperty("主键") private int id; @ExcelProperty("姓名") private String name; @ExcelProperty("性别") private String sex; @ExcelProperty("年龄") private String age; @ExcelProperty("账号") private String userName; @ExcelProperty("密码") private String passWord; @ExcelProperty("邮箱") private String email; }View Code
3.创建启动器和resource资源文件
//启动器 @SpringBootApplication public class testApplication { public static void main(String[] args) { SpringApplication.run(testApplication.class, args); } } //配置文件 server.port=8081View Code
4.创建一个测试Controller
@RestController @RequestMapping("test") public class testController { @GetMapping("/exportExcel") public void exportTable(HttpServletResponse response) throws IOException { List<User> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { User user = new User(); user.setId(1); user.setName("张三"); user.setAge("21"); list.add(user); } response.setContentType("application/vnd.ms-excel"); response.setHeader("content-disposition", "attachment;fileName=eventList.xlsx"); ExcelWriterBuilder builder = EasyExcel.write(response.getOutputStream(), userDto.class); ExcelWriterSheetBuilder sheet = builder.sheet(); ArrayList<userDto> dtos = new ArrayList<>(); for (User user : list) { userDto dto = new userDto(); BeanUtils.copyProperties(user, dto); dtos.add(dto); } sheet.doWrite(dtos); } }View Code
5.启动项目,页面上访问路径即可
标签:文件,String,boot,EasyExcel,ExcelProperty,导出,private,user,public From: https://www.cnblogs.com/foredawn/p/17247945.html