如果使用maven,请使用如下坐标
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.0</version>
</dependency>
实体类
@Data
public class Entity {
private Integer id;
@Excel(name = "姓名")
private String name;
//设置图片保存路径
@Excel(name = "图片", type = 2 ,width = 30 , height = 30,imageType = 1,savePath="D://")
private String img;
@Excel(name = "性别", replace = { "男_1", "女_2" }, suffix = "生")
private Integer sex;
@Excel(name = "出生日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", width = 20)
private Date birthday;
//无参函数不带导入解析会出错
public Entity() {
}
public Entity(Integer id, String name, String img, Integer sex, Date birthday) {
this.id = id;
this.name = name;
this.img = img;
this.sex = sex;
this.birthday = birthday;
}
}
导入代码片段
@RunWith(SpringRunner.class)
@SpringBootTest
public class easyPoiTest {
/**
* @Author
* @Description : 导出
* @Date 2020/11/30 16:34
**/
@Test
public void test1()throws IOException {
List<Entity> list = new ArrayList();
list.add(new Entity(1,"张三","C:\\Users\\shangpinyuan\\Pictures\\1.jpg",1,new Date()));
list.add(new Entity(2,"李四","C:\\Users\\shangpinyuan\\Pictures\\2.jpg",2,new Date()));
/**
* 导出参数对象
* 参数1 标题 如果不需要将title的参数设置为null即可
* 参数2 表的名字
*/
ExportParams exportParams = new ExportParams("所有数据","teacher");
/**
* exportExcel 导出Excel文件
* 参数1 导出参数对象
* 参数2 要导出的实体类的类对象
* 参数3 要导出的数据 需要一个集合
*
* 返回值就是封装好的文件对象
*/
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Entity.class, list);
workbook.write(new FileOutputStream("D:\\entity.xls"));
// 保存Excel文件到浏览器
// try {
// OutputStream output = response.getOutputStream();
// //清空缓存
// response.reset();
// //定义浏览器响应表头,顺带定义下载名,比如students(中文名需要转义)
// response.setHeader("Content-disposition", "attachment;filename="+new
// String("字段模板".getBytes(),"ISO-8859-1")+".xlsx");
// //定义下载的类型,标明是excel文件
// response.setContentType("application/vnd.ms-excel");
// //这时候把创建好的excel写入到输出流
// workbook.write(output);
// //养成好习惯,出门记得随手关门
// output.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
/**
* @Author
* @Description : 导入
* @Date 2020/11/30 16:34
**/
@Test
public void test2(String[] args) {
String filePath="D:\\entity.xls";
try {
ImportParams params = new ImportParams();
params.setHeadRows(1);
params.setTitleRows(1);
//设置文件是否保存
params.setNeedSave(true);
//设置保存路径
params.setSaveUrl("D:");
//此处解析为map
// List<Map<String, Object>> result1 = ExcelImportUtil.importExcel(new File(filePath), Map.class, params);
List<Entity> result = ExcelImportUtil.importExcel(new File(filePath), Entity.class, params);
for (Entity entity : result) {
System.out.println("entity = " + entity);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上传的文档如图所示