效果展示
全部导出
自定义导出
代码实现
1.引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.1</version>
</dependency>
2.实体类
@Data
public class User {
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "性别")
private Integer six;
@ExcelProperty(value = "年龄")
private Integer age;
@ExcelProperty(value = "地址")
private String address;
}
3.工具类
public class ExcelUtils {
private static String fileName = "导出" + System.currentTimeMillis() + ".xlsx";
public void write(Class head, List list) {
EasyExcel.write(fileName, head).sheet("模板").doWrite(list);
}
/**
* 动态列表导出
*/
public void write(Class head, Set<String> columns, List list) {
EasyExcel.write(fileName, head).includeColumnFiledNames(columns).sheet("模板").doWrite(list);
}
}
4.测试
public class ExcelTest {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User user = new User();
user.setAddress("地址" + i);
user.setAge(i);
user.setName("姓名" + i);
user.setSix(1);
users.add(user);
}
// 传参:指定字段
String column = "name,age";
if (StringUtils.isNotEmpty(column)) {
Set<String> columns = new HashSet<>(Arrays.asList(column.split(",")));
new ExcelHandle().write(User.class, columns, users);
} else {
new ExcelHandle().write(User.class, users);
}
}
}