easyexcel封裝工具類以及簡單使用方式
更新時間:2026年02月05日 14:43:41 作者:哀愁
文章介紹了如何使用封裝工具類、控制器和實(shí)體類進(jìn)行開發(fā),并通過Postman進(jìn)行測試,作者分享了個人經(jīng)驗(yàn),希望能對大家有所幫助
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
封裝工具類
package com.lk.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author : lk
* @date 2021/8/31 23:29
**/
@Slf4j
public class ExcelUtil {
public ExcelUtil() {
}
/**
* 導(dǎo)出execl
*
* @param response 響應(yīng)體
* @param list 數(shù)據(jù)
* @param clazz 類
* @param <T>
*/
public static <T> void downExcelUtil(HttpServletResponse response, List<T> list, Class<T> clazz) {
String fileName = System.currentTimeMillis() + "";
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// 這里URLEncoder.encode可以防止中文亂碼 當(dāng)然和easyexcel沒有關(guān)系
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
try {
int i = 0;
if (!list.isEmpty()) {
EasyExcel.write(response.getOutputStream(), clazz)
.registerWriteHandler(createTableStyle())
.sheet("data" + (i++))
.doWrite(list);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 文件上傳
* <p>
* 1. 創(chuàng)建excel對應(yīng)的實(shí)體對象
* <p>
* 2. 由于默認(rèn)一行行的讀取excel,所以需要創(chuàng)建excel一行一行的回調(diào)監(jiān)聽器,
* <p>
* 3. 直接讀即可
*/
public static <T> List<T> uploadExcel(MultipartFile file) throws IOException {
final List<T> rows = new ArrayList<T>();
ReadListener readListener = new AnalysisEventListener<T>() {
@Override
public void invoke(T data, AnalysisContext context) {
rows.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("read {} rows", rows.size());
}
};
EasyExcel.read(file.getInputStream(), null, readListener).sheet().doRead();
return rows;
}
public static <T> List<T> uploadExcel(MultipartFile file, Class<T> tClass) throws IOException {
final List<T> rowss = new ArrayList<T>();
ReadListener readListener = new AnalysisEventListener<T>() {
@Override
public void invoke(T data, AnalysisContext context) {
rowss.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("read {} rows", rowss.size());
}
};
EasyExcel.read(file.getInputStream(), tClass, readListener).sheet().doRead();
return rowss;
}
private static WriteHandler createTableStyle() {
// 頭的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景設(shè)置為紅色
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 設(shè)置字體
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 10);
headWriteFont.setBold(false);
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 內(nèi)容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
WriteFont contentWriteFont = new WriteFont();
// 字體大小
contentWriteFont.setFontHeightInPoints((short) 10);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 這個策略是 頭是頭的樣式 內(nèi)容是內(nèi)容的樣式 其他的策略可以自己實(shí)現(xiàn)
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
}
控制器
package com.lk.controller;
import com.lk.model.Student;
import com.lk.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author : lk
* @date 2021/8/31 22:19
**/
@RestController
@Slf4j
public class HelloController {
// 導(dǎo)出模版
@GetMapping("template")
public void template(HttpServletResponse response) {
ExcelUtil.downExcelUtil(response, new ArrayList<>(), Student.class);
}
// 上傳文件
@PostMapping("upload")
public void test02(@RequestParam("file") MultipartFile file) {
try {
List<Object> objects = ExcelUtil.uploadExcel(file);
log.info("studnets:{}", objects);
} catch (IOException e) {
e.printStackTrace();
}
}
}
實(shí)體類
package com.lk.model;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author : lk
* @date 2021/8/31 22:19
**/
@Data
public class Student {
@ExcelProperty(value = "編號")
private String id;
@ExcelProperty(value = "學(xué)生姓名")
private String name;
@ExcelProperty(value = "年齡")
private Integer age;
}
使用postman測試

總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)身份證號碼驗(yàn)證源碼示例分享
本篇文章主要介紹了Java實(shí)現(xiàn)身份證號碼驗(yàn)證源碼示例分享,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
詳解spring cloud hystrix請求緩存(request cache)
這篇文章主要介紹了詳解spring cloud hystrix請求緩存(request cache),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Java Floyd算法求有權(quán)圖(非負(fù)權(quán))的最短路徑并打印
這篇文章主要介紹了Java Floyd算法求有權(quán)圖(非負(fù)權(quán))的最短路徑并打印,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Spring?Boot整合流控組件Sentinel的場景分析
Sentinel?提供簡單易用、完善的?SPI?擴(kuò)展接口。您可以通過實(shí)現(xiàn)擴(kuò)展接口來快速地定制邏輯,這篇文章主要介紹了Spring?Boot整合流控組件Sentinel的過程解析,需要的朋友可以參考下2021-12-12
JavaMail實(shí)現(xiàn)帶附件的郵件發(fā)送
這篇文章主要為大家詳細(xì)介紹了JavaMail實(shí)現(xiàn)帶附件的郵件發(fā)送,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08
將本地jar包安裝進(jìn)入maven倉庫(實(shí)現(xiàn)方法)
下面小編就為大家?guī)硪黄獙⒈镜豭ar包安裝進(jìn)入maven倉庫(實(shí)現(xiàn)方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

