Article directory
EasyExcel
EasyExcel is a Java-based, fast and concise Excel processing tool that solves memory overflow of large files.
It allows you to quickly complete Excel's reading, writing and other functions without considering performance, memory and other factors.
Introduce dependencies
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
```# 表结构
```java
CREATE TABLE `student` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '学生表ID',
`sname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '学生姓名',
`sno` bigint NOT NULL COMMENT '学号',
`sex` char(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '性别',
`age` int NOT NULL COMMENT '年龄',
`is_deleted` tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT '是否删除',
PRIMARY KEY (`id`)
);
Some data has been imported into the uploaded article before, so now there is data in the table and can be exported directly.
Project structure
Export template class
@Data
public class StudentVo {
/**学生姓名**/
@ExcelProperty(value = "姓名",index = 0)
private String sname;
/**学号**/
@ExcelProperty(value = "学号",index = 1)
private Long sno;
/**性别**/
@ExcelProperty(value = "性别",index = 2)
private String sex;
/**年龄**/
@ExcelProperty(value = "年龄",index = 3)
private Integer age;
}
Controller
@RestController
@RequestMapping("/easyExcel")
public class EasyExcelController {
@Resource
private IStudentService studentService;
@PostMapping("/studentExport")
public void studentExport(HttpServletResponse response){
studentService.studentExport(response);
}
}
Service
public interface IStudentService extends IService<Student> {
void studentExport(HttpServletResponse response);
}
ServiceImpl
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
@Resource
private StudentMapper studentMapper;
@Override
public void studentExport(HttpServletResponse response) {
try {
String fileName = "student";
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
WriteSheet studentInfo = EasyExcel.writerSheet(0,"student")
.head(StudentVo.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.build();
List<Student> studentList = studentMapper.selectList(null);
excelWriter.write(studentList,studentInfo);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
excelWriter.finish();
}catch (IOException e){
e.printStackTrace();
}
}
}
mapper
public interface StudentMapper extends BaseMapper<Student> {
}
Startup project
PostMan test
Export successful