最新版easyExcel工具類.md
阿新 • • 發佈:2020-08-29
最新版的easyexcel2.0升級後原有的匯入匯出書寫方法就已經過時了,本文記錄了最新版的EasyExcel工具類的整合與使用。最新版書寫比原來要簡單不少,效能也有所提高,推薦換到最新版。
引入最新的依賴
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.6</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency>
主要用到了easyexcel
、hutool
工具類和lombok
外掛
匯入匯出的實體類
package org.geekboy.bean; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; import lombok.Data; /** * @ClassName ExportModel * @Description 匯出模型 * @Author zhangwei * @Version 1.0.0 * @Date 2020/4/1 20:55 */ @ContentRowHeight(20) @HeadRowHeight(25) @ColumnWidth(25) @Data public class ExportModel { @ExcelProperty(value = "姓名" ,index = 0) private String name; @ExcelProperty(value = "性別" ,index = 1) private String sex; @ExcelProperty(value = "年齡" ,index = 2) private Integer age; }
package org.geekboy.bean; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data; /** * @ClassName ImportModel * @Description 匯入模型 * @Author zhangwei * @Version 1.0.0 * @Date 2020/4/1 20:54 */ @Data public class ImportModel { @ExcelProperty(index = 0) private String date; @ExcelProperty(index = 1) private String author; @ExcelProperty(index = 2) private String book; }
匯入匯出工具類
package org.geekboy.common;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* @Author zhang wei
* @Description 監聽類
* @Date 2020-08-13
*/
public class ExcelListener extends AnalysisEventListener {
/**
* 可以通過例項獲取該值
*/
private List<Object> dataList = new ArrayList<>();
@Override
public void invoke(Object object, AnalysisContext context) {
//資料儲存到list,供批量處理,或後續自己業務邏輯處理。
dataList.add(object);
handleBusinessLogic();
/*
如資料過大,可以進行定量分批處理
if(dataList.size()>=200){
handleBusinessLogic();
dataList.clear();
}
*/
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//非必要語句,檢視匯入的資料
System.out.println("匯入的資料條數為: " + dataList.size());
}
//根據業務自行實現該方法,例如將解析好的dataList儲存到資料庫中
private void handleBusinessLogic() {
}
public List<Object> getDataList() {
return dataList;
}
public void setDataList(List<Object> dataList) {
this.dataList = dataList;
}
}
package org.geekboy.common;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Author zhang wei
* @Description Excel讀寫工具類
* @Date 2020-08-13
*/
public class ExcelUtil {
/**
* 讀取Excel(多個sheet可以用同一個實體類解析)
* @param excelInputStream
* @param fileName
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> readExcel(InputStream excelInputStream, String fileName,Class<T> clazz) {
ExcelListener excelListener = new ExcelListener();
ExcelReader excelReader = getReader(excelInputStream, fileName,clazz, excelListener);
if (excelReader == null) {
return new ArrayList<>();
}
List<ReadSheet> readSheetList = excelReader.excelExecutor().sheetList();
for (ReadSheet readSheet : readSheetList) {
excelReader.read(readSheet);
}
excelReader.finish();
return Convert.toList(clazz, excelListener.getDataList());
}
/**
* 匯出Excel(一個sheet)
*
* @param response HttpServletResponse
* @param list 資料list
* @param fileName 匯出的檔名
* @param sheetName 匯入檔案的sheet名
* @param clazz 實體類
*/
public static <T> void writeExcel(HttpServletResponse response, List<T> list, String fileName, String sheetName, Class<T> clazz) {
OutputStream outputStream = getOutputStream(response, fileName);
ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build();
WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
excelWriter.write(list, writeSheet);
excelWriter.finish();
}
/**
* 匯出時生成OutputStream
*/
private static OutputStream getOutputStream(HttpServletResponse response, String fileName) {
//建立本地檔案
String filePath = fileName + ".xlsx";
File file = new File(filePath);
try {
if (!file.exists() || file.isDirectory()) {
file.createNewFile();
}
fileName = new String(filePath.getBytes(), "ISO-8859-1");
response.addHeader("Content-Disposition", "filename=" + fileName);
return response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 返回ExcelReader
*
* @param excel 檔案
* @param clazz 實體類
* @param excelListener
*/
private static <T> ExcelReader getReader(InputStream inputStream, String filename, Class<T> clazz, ExcelListener excelListener) {
try {
if (filename == null ||
(!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
return null;
}
ExcelReader excelReader = EasyExcel.read(inputStream, clazz, excelListener).build();
inputStream.close();
return excelReader;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
測試類
package org.geekboy.test;
import org.geekboy.bean.ExportModel;
import org.geekboy.bean.ImportModel;
import org.geekboy.common.ExcelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Controller
public class ExcelTestController {
@PostMapping(value = "/import")
public List<ImportModel> read(MultipartFile excel) throws IOException {
return ExcelUtil.readExcel(excel.getInputStream(), excel.getOriginalFilename(), ImportModel.class);
}
@GetMapping(value = "/export")
public void writeExcel(HttpServletResponse response) {
List<ExportModel> list = getList();
String fileName = "Excel匯出測試";
String sheetName = "sheet1";
ExcelUtil.writeExcel(response, list, fileName, sheetName, ExportModel.class);
}
private List<ExportModel> getList() {
List<ExportModel> modelList = new ArrayList<>();
ExportModel firstModel = new ExportModel();
firstModel.setName("李明");
firstModel.setSex("男");
firstModel.setAge(20);
modelList.add(firstModel);
ExportModel secondModel = new ExportModel();
secondModel.setName("珍妮");
secondModel.setSex("女");
secondModel.setAge(19);
modelList.add(secondModel);
return modelList;
}
}