一、EasyExcel的介紹
EasyExcel 是一款基于 Java 的簡(jiǎn)單易用的 Excel 文件操作工具。它提供了豐富的 API,可以方便地讀取、寫入和操作 Excel 文件,支持常見的 Excel 操作,如讀取/寫入單元格數(shù)據(jù)、合并單元格、設(shè)置樣式、處理大數(shù)據(jù)量等。EasyExcel能大大減少占用內(nèi)存的主要原因是在解析Excel時(shí)沒有將文件數(shù)據(jù)一次性全部加載到內(nèi)存中,而是從磁盤上一行行讀取數(shù)據(jù),逐個(gè)解析。
1、讀取 Excel 文件
使用 EasyExcel 可以讀取 Excel 文件的內(nèi)容并將其轉(zhuǎn)化為 Java 對(duì)象,或者按行進(jìn)行處理。例如:
// 讀取 Excel 文件內(nèi)容并轉(zhuǎn)化為 Java 對(duì)象
List<User> userList = EasyExcel.read("path/to/excel.xlsx").sheet().doReadSync(User.class);
// 按行處理 Excel 文件
EasyExcel.read("path/to/excel.xlsx").sheet().doReadSync(new AnalysisEventListener<User>() {
@Override
public void invoke(User user, AnalysisContext context) {
// 處理每行數(shù)據(jù)
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 處理完成后的回調(diào)
}
});
2、寫入 Excel 文件
EasyExcel 提供了方便的 API 來寫入數(shù)據(jù)到 Excel 文件中。例如:
// 寫入 Java 對(duì)象到 Excel 文件
EasyExcel.write("path/to/excel.xlsx").sheet().doWrite(userList);
// 寫入指定數(shù)據(jù)到 Excel 文件
List<List<Object>> data = new ArrayList<>();
// 添加數(shù)據(jù)到 data 列表...
EasyExcel.write("path/to/excel.xlsx").sheet().doWrite(data);
3、設(shè)置樣式和操作單元格
EasyExcel 允許你設(shè)置單元格的樣式、合并單元格、設(shè)置表頭等操作。例如:
// 設(shè)置表頭
List<List<String>> head = new ArrayList<>();
// 添加表頭數(shù)據(jù)到 head 列表...
EasyExcel.write("path/to/excel.xlsx").head(head).sheet().doWrite(data);
// 設(shè)置單元格樣式
WriteCellStyle style = new WriteCellStyle();
// 設(shè)置樣式屬性...
WriteSheet sheet = EasyExcel.writerSheet(0).build();
sheet.setCellStyle(style);
EasyExcel.write("path/to/excel.xlsx").sheet(sheet).doWrite(data);
// 合并單元格
WriteSheet sheet = EasyExcel.writerSheet(0).build();
sheet.setAutomaticMergeHead(true); // 自動(dòng)合并表頭
sheet.merge(firstRow, lastRow, firstCol, lastCol); // 合并單元格
EasyExcel.write("path/to/excel.xlsx").sheet(sheet).doWrite(data);
4、大數(shù)據(jù)量處理
EasyExcel 提供了一些特性來處理大數(shù)據(jù)量的 Excel 文件,如使用滑動(dòng)窗口來限制內(nèi)存占用、使用回調(diào)接口來處理每行數(shù)據(jù)等。這些特性可以幫助你高效地處理大型 Excel 文件而不會(huì)導(dǎo)致內(nèi)存溢出。例如:
// 大數(shù)據(jù)量寫入
EasyExcel.write("path/to/excel.xlsx", User.class).sheet().registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(userList);
二、完整示例(將用戶表導(dǎo)出導(dǎo)入):
1、在pom.xml引入依賴
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
2、創(chuàng)建導(dǎo)出實(shí)體類跟表頭
**
* 用戶 Excel 導(dǎo)出 VO
*/
@Data
public class UserExcelVO {
@ExcelProperty("用戶編號(hào)")
private Long id;
@ExcelProperty("用戶名稱")
private String username;
@ExcelProperty("用戶昵稱")
private String nickname;
@ExcelProperty("用戶郵箱")
private String email;
@ExcelProperty("手機(jī)號(hào)碼")
private String mobile;
@ExcelProperty(value = "用戶性別", converter = DictConvert.class)
@DictFormat(DictTypeConstants.USER_SEX)
private Integer sex;
@ExcelProperty(value = "帳號(hào)狀態(tài)", converter = DictConvert.class)
@DictFormat(DictTypeConstants.COMMON_STATUS)
private Integer status;
@ExcelProperty("最后登錄IP")
private String loginIp;
@ExcelProperty("最后登錄時(shí)間")
private LocalDateTime loginDate;
@ExcelProperty("部門名稱")
private String deptName;
@ExcelProperty("部門負(fù)責(zé)人")
private String deptLeaderNickname;
}
① 每個(gè)字段上的 @ExcelProperty (opens new window)注解,聲明 Excel Head 頭部的名字
② 每個(gè)字段的值,就是它對(duì)應(yīng)的 Excel Row 行的數(shù)據(jù)值
③ @ExcelProperty 注解的 converter 屬性是 DictConvert 轉(zhuǎn)換器,通過它將 status = 1 轉(zhuǎn)換成“開啟”列,status = 0 轉(zhuǎn)換成”禁用”列,注解 @DictFormat (opens new window)為對(duì)應(yīng)的字典數(shù)據(jù)的類型。
更多《EasyExcel 中的注解 》文章來源:http://www.zghlxwxcb.cn/news/detail-654318.html
3、ExcelUtils類 寫入以及讀取
public class ExcelUtils {
/**
* 將列表以 Excel 響應(yīng)給前端
*
* @param response 響應(yīng)
* @param filename 文件名
* @param sheetName Excel sheet 名
* @param head Excel head 頭
* @param data 數(shù)據(jù)列表哦
* @param <T> 泛型,保證 head 和 data 類型的一致性
* @throws IOException 寫入失敗的情況
*/
public static <T> void write(HttpServletResponse response, String filename, String sheetName,
Class<T> head, List<T> data) throws IOException {
// 輸出 Excel
EasyExcel.write(response.getOutputStream(), head)
.autoCloseStream(false) // 不要自動(dòng)關(guān)閉,交給 Servlet 自己處理
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 長(zhǎng)度,自動(dòng)適配。最大 255 寬度
.sheet(sheetName).doWrite(data);
// 設(shè)置 header 和 contentType。寫在最后的原因是,避免報(bào)錯(cuò)時(shí),響應(yīng) contentType 已經(jīng)被修改了
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
}
public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
return EasyExcel.read(file.getInputStream(), head, null)
.autoCloseStream(false) // 不要自動(dòng)關(guān)閉,交給 Servlet 自己處理
.doReadAllSync();
}
}
4、Controller類實(shí)現(xiàn)
@GetMapping("/export")
@Operation(summary = "導(dǎo)出用戶")
@OperateLog(type = EXPORT)
public void exportUserList(@Validated UserExportReqVO reqVO,
HttpServletResponse response) throws IOException {
// 獲得用戶列表
List<UserDO> users = userService.getUserList(reqVO);
UserExcelVO excelVO = UserConvert.INSTANCE.convert02(user);
// 輸出
ExcelUtils.write(response, "用戶數(shù)據(jù).xls", "用戶列表", UserExcelVO.class, excelVO );
}
@PostMapping("/import")
@Operation(summary = "導(dǎo)入用戶")
@Parameters({
@Parameter(name = "file", description = "Excel 文件", required = true),
@Parameter(name = "updateSupport", description = "是否支持更新,默認(rèn)為 false", example = "true")
})
public void importExcel(@RequestParam("file") MultipartFile file,
@RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
}
5、前端導(dǎo)入實(shí)現(xiàn)
文章來源地址http://www.zghlxwxcb.cn/news/detail-654318.html
到了這里,關(guān)于springboot中使用EasyExcel實(shí)現(xiàn)Excel 導(dǎo)入導(dǎo)出的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!