https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write
Pom 引入
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<!-- easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
EasyExcel 使用(Web)
实体类
- 注解ExcelProperty :标注name字段的excel列名
@Data
public class DemoData {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private String age;
}
controller
@Controller
public class ExcelUtils {
@GetMapping("download")
public void download(HttpServletResponse response) {
String fileName = encodeFileName("fileName");
String sheetName = "sheetName";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 分页导出数据
List<DemoData> data = data();
Lists.partition(data, 200).forEach(subData -> {
try {
EasyExcel.write(response.getOutputStream(), DemoData.class)
.sheet(sheetName)
.doWrite(subData);
} catch (IOException e) {
e.printStackTrace();
}
});
}
private String encodeFileName(String fileName) {
try {
// 这里URLEncoder.encode可以防止中文乱码
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
// 读取数据
private List<DemoData> data() {
List<DemoData> list = new ArrayList<>();
DemoData demoData = new DemoData();
demoData.setName("name");
demoData.setAge("18");
list.add(demoData);
return list;
}
}