需求說明
之前說了用freemarker來導出word,這次來簡單的說一下通過easypoi導出Excel。
具體實現
1.目標數據
如圖:
2.引入easypoi依賴包
可以直接從maven倉庫下載
<!-- 引入easypoi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
3.給需要導出的字段添加註解
這邊只處理了3個字段
@Setter
@Getter
public class User {
private Integer id; // 用戶id
@Excel(name = "賬號", width=20)
private String userName; // 用戶賬號
@Excel(name = "暱稱", width=20)
private String nickName; // 用戶暱稱
@Excel(name = "密碼", width=20)
private String password; // 用戶密碼
private String salt; // 加密密碼的鹽
private Integer status; // 用戶狀態,0:創建未認證(比如沒有激活,沒有輸入驗證碼等) --等待驗證的用戶,1:正常狀態,2:用戶被鎖定
private String age; // 用戶年齡
private String sex; // 用戶性別
private String mail; // 用戶郵箱
private String photo; // 用戶頭像
}
注意:
@Excel中有不少屬性,這邊只用了到了name和width,默認情況下導出的寬度太擠了,所以調大了些。
如果想要了解更多的屬性,可以參考EasyPoi教程:http://easypoi.mydoc.io/#text_197838
4.代碼調用
/**
* Description: 通過easypoi導出Excel
*
* @param request
* @param response
*
*/
@RequestMapping(value = "/exportUserByExcel", method=RequestMethod.GET)
public void exportUserByExcel(HttpServletRequest request, HttpServletResponse response) {
List<User> users = userService.findByList();
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), User.class, users);
try {
String name = "用戶數據.xls";
String fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
workbook.write(response.getOutputStream());
response.flushBuffer();
logger.info("用戶數據導出成功");
} catch (IOException e) {
logger.error("用戶數據導出失敗,原因:", e);
} finally {
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.調用結果
如圖:
6.說明
雖然只是簡單的嘗試的用了一下,不過感覺還真是好用!
參考資料:
http://easypoi.mydoc.io/#text_197838