入門實例
基於maven項目
1.導包
<!-- easypoi的支持 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
@ExcelTarget("emp")
public class POIEmployee {
/**
@Excel:代表這個字段要生成到excel中去
*/
private Long id;
//name:這個excel的表頭名稱
@Excel(name = "用戶名")
private String username;
//width:格子的寬度
@Excel(name = "郵箱",width=20)
private String email;
@Excel(name = "年齡")
private Integer age;
//replace:替換 true就會顯示男,false顯示女
@Excel(name = "性別", replace = { "男_true", "女_false" })
private Boolean sex;
//format:導入和導出的日期格式 注:如果數據庫是varchar,還需要配置databaseFormat
@Excel(name = "出生日期",width = 20,format="yyyy-MM-dd HH:mm:ss")
private Date bornDate = new Date();
//type=2代表它是一張圖片
@Excel(name = "頭像",type = 2 ,width = 20 , height = 20)
private String headImage;
@ExcelEntity
private POIDepartment department;
...
}
public class Department {
private Long id;
@Excel(name = "部門名稱_emp") //@ExcelEntity(id="emp"):對應另一個關連對象
private String name;
}
3.測試代碼
導出
public class EasyPOITest {
//導出
@Test
public void test() throws Exception{
POIDepartment d1 = new POIDepartment();
d1.setId(1L);
d1.setName("俱樂部");
POIEmployee e1 = new POIEmployee();
e1.setId(1L);
e1.setUsername("小王");
e1.setEmail("[email protected]");
e1.setAge(12);
e1.setSex(true);
e1.setHeadImage("images/1.png");
e1.setDepartment(d1);
POIEmployee e2 = new POIEmployee();
e2.setId(2L);
e2.setUsername("小李");
e2.setEmail("[email protected]");
e2.setAge(18);
e2.setSex(false);
e2.setHeadImage("images/3.png");
e2.setDepartment(d1);
//準備數據(以後是直接讀取這些數據)
List<POIEmployee> list = new ArrayList<>();
list.add(e1);
list.add(e2);
/**
* 參數一:導出的一些屬性
* title:標題 sheetName:表名
* 參數二:導出的數據類型
* 參數三:導出的數據
*/
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("員工信息","員工數據"),POIEmployee.class, list);
////保存數據,輸出
FileOutputStream out = new FileOutputStream("emphaha.xlsx");
workbook.write(out);
out.close();
}
}
導入
@Test
public void test2() {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
List<PoiUser> list = ExcelImportUtil.importExcel(new File("員工.xlsx"), PoiUser.class, params);
}