1. 程式人生 > 實用技巧 >EasyPoi 簡單匯入匯出

EasyPoi 簡單匯入匯出

匯入邏輯

public ResultMsg importUser(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        List<UserImportExcel> list = ExcelImportUtil.importExcel(file.getInputStream(), UserImportExcel.class, params);
        list.forEach(user 
-> log.info(JSONObject.toJSONString(user))); return null; }

匯出邏輯

public void exportUser(@RequestBody ListUser param, HttpServletResponse response) throws IOException {
        List<UserExportExcel> result = service.listNoLimit(param);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader(
"Content-disposition", "attachment;filename=myExcel.xls"); @Cleanup OutputStream ouputStream = null; Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("使用者匯出", "使用者"), UserExportExcel.class, result); try { ouputStream = response.getOutputStream(); workbook.write(ouputStream); }
catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(ouputStream); IOUtils.closeQuietly(workbook); } }

操作實體類

package com.user.model;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

/**
 * @author SZRD_A2 SXT
 * @version V1.0
 * @date 2020/12/29 0029 15:48
 */

@Data
public class UserImportExcel {

    @Excel(name = "姓名", width = 24, fixedIndex = 1)
    private String name;

    @Excel(name = "工號", width = 24, fixedIndex = 2)
    private String id;

    @Excel(name = "手機號", width = 24, fixedIndex = 3)
    private String phone;

    @Excel(name = "部門", width = 24, fixedIndex = 4)
    private String department;
}

maven配置



<properties>
<easypoi.version>4.2.0</easypoi.version>
<apache.poi.version>4.1.2</apache.poi.version>
</properties>


<dependencies>

<!-- easypoi --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>${easypoi.version}</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>${easypoi.version}</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>${easypoi.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${apache.poi.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${apache.poi.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>${apache.poi.version}</version> </dependency>
</dependencies>