这是我自己写的通用导出excel类。对于简单的excel导出,不需要写代码,只需要两步:
1、在需要导出的字段上加上@ExcelColumn(value = "真实姓名",sort = 2)注解。其中value是表头,sort是列的排序。
2、导出时,将list传入方法即可完成自动导出到浏览器并且自动下载成功 ExcelUtil.export(data, response);
示例代码如下:
第一步:在需要导出成excel的实体类的字段上加上注解
public class User {
@ExcelColumn(value = "序号",sort = 1)
private Integer id;
@ExcelColumn(value = "用户名",sort = 5)
private String userName;
private String passWord;
@ExcelColumn(value = "真实姓名",sort = 2)
private String realName;
}
第二步:将list和response传入方法中
@RequestMapping(value = "export", method = RequestMethod.GET)
public void exportByBeans(HttpServletResponse response) throws Exception {
User user1 = new User();
user1.setId(1);
user1.setUserName("Zhang San");
user1.setRealName("张三");
User user2 = new User();
user2.setId(2);
user2.setUserName("Li Si");
user2.setRealName("李四");
List<User> data = new ArrayList<>();
data.add(user1);
data.add(user2);
data.add(user3);
ExcelUtil.export(data, response);//这一行才是重点
}