天天看點

SpringBoot內建EasyPoi的基本使用(注解導出)

首先,在SpringBoot中使用EasyPoi少不了包的內建,在這裡提供了EasyPoi的包:

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.0.0</version>
</dependency>
           

對于浏覽器中的表的資料,需要在我們的實體類中将資料的字段與屬性一一對應進行封裝,使用@Excel注解進行注解導出,每列資料的列名使用@Excel(name屬性),代碼如下所示:

public class StudentClient implements Serializable {

    @Excel(name = "手機号")
    private String mobile;

    @Excel(name = "姓名")
    private String name;
           

對于一些字段,查找出的資料與導出的資料内容不一緻,屬于一種對應關系,如:1對應男,2對應女,想要進行對應關系的轉換,可使用@Excel的replace屬性;如下所示:

@Excel(name = "學生性别", replace = { "男_1", "女_2" })
private int sex;
           

具體其它一些屬性暫不細說,有需要的小夥伴可檢視開發文檔:

http://doc.wupaas.com/docs/easypoi/easypoi-1c0u9d9lcruu2

一:Excel檔案本地導出

在資料所對應的實體類封裝好之後,就可以進行導出功能的代碼編寫了。做一個簡單的本地導出資料;

List<StudentClient > list = new ArrayList<StudentClient>();
for (int i = 0; i < 5; i++) {
    StudentClient client = new StudentClient();
    client.setClientName("小廖" + i);
    client.setClientPhone("438" + i);
    client.setRemark("測試" + i);
    list.add(client);
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("測試", "測試"), StudentClient.class, list);
File savefile = new File("D:/excel/");
if (!savefile.exists()) {
    savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("D:/excel/ExcelExport.xlsx");
workbook.write(fos);
fos.close();
           

感謝愛心觀衆小廖的參加,導出資料效果圖如下:

SpringBoot內建EasyPoi的基本使用(注解導出)

二:浏覽器導出Excel檔案

在平常的開發中,多用于浏覽器資料導出,上面算一個小小的入門;在浏覽器中資料導出檔案;擷取響應對象進行編碼格式等一系列設定;然後使用流進行資料輸出就OK了。簡簡單單的操作,快速上手。

Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), Class, Object);
HttpServletResponse response = WebUtils.response();// 擷取響應對象
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");// 設定編碼格式
String fileName = URLEncoder.encode(title, "utf-8");// 設定檔案名和格式
response.setHeader("Content-dispodition", "attachment;filename="+fileName);
ServletOutputStream outputStream = response.getOutputStream();// 擷取輸出流
workbook.write(outputStream);// 輸出
outputStream.close();// 關流
           

文章到這裡就結束了!!!