所需依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
只需将下面三个类copy进项目、即可实现Excel的导入导出功能
注:第二个和第三个类,非必须的,只不过是对功能加强,工具类里面的方法部分依赖下面两个类。(为工具类完整性,最好添加进项目里)
1:EasyExcelUtil
Excel工具类
2:DefaultExcelListener
异步监听对Excel操作
3:EasyExcelWriterFactory
链式导出多个sheet的Excel
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.handler.WriteHandler;
import org.apache.poi.ss.formula.functions.T;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Author: ww
* Datetime: 2020\8\12 0012
* Description: 注:如果方法中无以下参数,则使用默认值
* Integer sheetNo 默认0读取第一张sheet
* Integer headRowNum 默认1不读取首行,从第二行开始读取
* 返回值return:List<Map<Integer,String>>: Integer:列数 String:列数对应的value
*/
public class EasyExcelUtil {
/**
* 同步无模型读(默认读取sheet0,从第2行开始读)
* @param filePath excel文件的绝对路径
*/
public static List<Map<Integer, String>> syncRead(String filePath){
return EasyExcelFactory.read(filePath).sheet().doReadSync();
}
/**
* 同步无模型读(自定义读取sheetX,从第2行开始读)
* @param filePath excel文件的绝对路径
* @param sheetNo sheet页号,从0开始
*/
public static List<Map<Integer, String>> syncRead(String filePath, Integer sheetNo){
return EasyExcelFactory.read(filePath).sheet(sheetNo).doReadSync();
}
/**
* 同步无模型读(指定sheet和表头占的行数)
* @param filePath
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<Map<Integer, String>> syncRead(String filePath, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(filePath).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
}
/**
* 同步无模型读(指定sheet和表头占的行数)
* @param inputStream
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<Map<Integer, String>> syncRead(InputStream inputStream, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(inputStream).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
}
/**
* 同步无模型读(指定sheet和表头占的行数)
* @param file
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<Map<Integer, String>> syncRead(File file, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(file).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
}
//====================================================无JAVA模型读取excel数据===============================================================
//====================================================将excel数据同步到JAVA模型属性里===============================================================
/**
* 同步按模型读(默认读取sheet0,从第2行开始读)
* @param filePath
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
*/
public static List<T> syncReadModel(String filePath, Class clazz){
return EasyExcelFactory.read(filePath).sheet().head(clazz).doReadSync();
}
/**
* 同步按模型读(默认表头占一行,从第2行开始读)
* @param filePath
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
*/
public static List<T> syncReadModel(String filePath, Class clazz, Integer sheetNo){
return EasyExcelFactory.read(filePath).sheet(sheetNo).head(clazz).doReadSync();
}
/**
* 同步按模型读(指定sheet和表头占的行数)
* @param inputStream
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<T> syncReadModel(InputStream inputStream, Class clazz, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(inputStream).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
}
/**
* 同步按模型读(指定sheet和表头占的行数)
* @param file
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<T> syncReadModel(File file, Class clazz, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(file).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
}
/**
* 同步按模型读(指定sheet和表头占的行数)
* @param filePath
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static List<T> syncReadModel(String filePath, Class clazz, Integer sheetNo, Integer headRowNum){
return EasyExcelFactory.read(filePath).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
}
/**
* 异步无模型读(默认读取sheet0,从第2行开始读)
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param filePath 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener){
EasyExcelFactory.read(filePath, excelListener).sheet().doRead();
}
/**
* 异步无模型读(默认表头占一行,从第2行开始读)
* @param filePath 表头占的行数,从0开始(如果要连表头一起读出来则传0)
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param sheetNo sheet页号,从0开始
*/
public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener, Integer sheetNo){
EasyExcelFactory.read(filePath, excelListener).sheet(sheetNo).doRead();
}
/**
* 异步无模型读(指定sheet和表头占的行数)
* @param inputStream
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncRead(InputStream inputStream, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(inputStream, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 异步无模型读(指定sheet和表头占的行数)
* @param file
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncRead(File file, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(file, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 异步无模型读(指定sheet和表头占的行数)
* @param filePath
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
* @return
*/
public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(filePath, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 异步按模型读取(默认读取sheet0,从第2行开始读)
* @param filePath
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
*/
public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz){
EasyExcelFactory.read(filePath, clazz, excelListener).sheet().doRead();
}
/**
* 异步按模型读取(默认表头占一行,从第2行开始读)
* @param filePath
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
*/
public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo){
EasyExcelFactory.read(filePath, clazz, excelListener).sheet(sheetNo).doRead();
}
/**
* 异步按模型读取
* @param inputStream
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncReadModel(InputStream inputStream, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(inputStream, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 异步按模型读取
* @param file
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncReadModel(File file, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(file, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 异步按模型读取
* @param filePath
* @param excelListener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等
* @param clazz 模型的类类型(excel数据会按该类型转换成对象)
* @param sheetNo sheet页号,从0开始
* @param headRowNum 表头占的行数,从0开始(如果要连表头一起读出来则传0)
*/
public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum){
EasyExcelFactory.read(filePath, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
}
/**
* 无模板写文件
* @param filePath
* @param head 表头数据
* @param data 表内容数据
*/
public static void write(String filePath, List<List<String>> head, List<List<Object>> data){
EasyExcel.write(filePath).head(head).sheet().doWrite(data);
}
/**
* 无模板写文件
* @param filePath
* @param head 表头数据
* @param data 表内容数据
* @param sheetNo sheet页号,从0开始
* @param sheetName sheet名称
*/
public static void write(String filePath, List<List<String>> head, List<List<Object>> data, Integer sheetNo, String sheetName){
EasyExcel.write(filePath).head(head).sheet(sheetNo, sheetName).doWrite(data);
}
/**
* 根据excel模板文件写入文件
* @param filePath
* @param templateFileName
* @param headClazz
* @param data
*/
public static void writeTemplate(String filePath, String templateFileName, Class headClazz, List data){
EasyExcel.write(filePath, headClazz).withTemplate(templateFileName).sheet().doWrite(data);
}
/**
* 根据excel模板文件写入文件
* @param filePath
* @param templateFileName
* @param data
*/
public static void writeTemplate(String filePath, String templateFileName, List data){
EasyExcel.write(filePath).withTemplate(templateFileName).sheet().doWrite(data);
}
/**
* 按模板写文件
* @param filePath
* @param headClazz 表头模板
* @param data 数据
*/
public static void write(String filePath, Class headClazz, List data){
EasyExcel.write(filePath, headClazz).sheet().doWrite(data);
}
/**
* 按模板写文件
* @param filePath
* @param headClazz 表头模板
* @param data 数据
* @param sheetNo sheet页号,从0开始
* @param sheetName sheet名称
*/
public static void write(String filePath, Class headClazz, List data, Integer sheetNo, String sheetName){
EasyExcel.write(filePath, headClazz).sheet(sheetNo, sheetName).doWrite(data);
}
/**
* 按模板写文件
* @param filePath
* @param headClazz 表头模板
* @param data 数据
* @param writeHandler 自定义的处理器,比如设置table样式,设置超链接、单元格下拉框等等功能都可以通过这个实现(需要注册多个则自己通过链式去调用)
* @param sheetNo sheet页号,从0开始
* @param sheetName sheet名称
*/
public static void write(String filePath, Class headClazz, List data, WriteHandler writeHandler, Integer sheetNo, String sheetName){
EasyExcel.write(filePath, headClazz).registerWriteHandler(writeHandler).sheet(sheetNo, sheetName).doWrite(data);
}
/**
* 按模板写文件(包含某些字段)
* @param filePath
* @param headClazz 表头模板
* @param data 数据
* @param includeCols 包含字段集合,根据字段名称显示
* @param sheetNo sheet页号,从0开始
* @param sheetName sheet名称
*/
public static void writeInclude(String filePath, Class headClazz, List data, Set<String> includeCols, Integer sheetNo, String sheetName){
EasyExcel.write(filePath, headClazz).includeColumnFiledNames(includeCols).sheet(sheetNo, sheetName).doWrite(data);
}
/**
* 按模板写文件(排除某些字段)
* @param filePath
* @param headClazz 表头模板
* @param data 数据
* @param excludeCols 过滤排除的字段,根据字段名称过滤
* @param sheetNo sheet页号,从0开始
* @param sheetName sheet名称
*/
public static void writeExclude(String filePath, Class headClazz, List data, Set<String> excludeCols, Integer sheetNo, String sheetName){
EasyExcel.write(filePath, headClazz).excludeColumnFiledNames(excludeCols).sheet(sheetNo, sheetName).doWrite(data);
}
/**
* 多个sheet页的数据链式写入
* ExcelUtil.writeWithSheets(outputStream)
* .writeModel(ExcelModel.class, excelModelList, "sheetName1")
* .write(headData, data,"sheetName2")
* .finish();
* @param outputStream
*/
public static EasyExcelWriterFactory writeWithSheets(OutputStream outputStream){
EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(outputStream);
return excelWriter;
}
/**
* 多个sheet页的数据链式写入
* ExcelUtil.writeWithSheets(file)
* .writeModel(ExcelModel.class, excelModelList, "sheetName1")
* .write(headData, data,"sheetName2")
* .finish();
* @param file
*/
public static EasyExcelWriterFactory writeWithSheets(File file){
EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(file);
return excelWriter;
}
/**
* 多个sheet页的数据链式写入
* ExcelUtil.writeWithSheets(filePath)
* .writeModel(ExcelModel.class, excelModelList, "sheetName1")
* .write(headData, data,"sheetName2")
* .finish();
* @param filePath
*/
public static EasyExcelWriterFactory writeWithSheets(String filePath){
EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(filePath);
return excelWriter;
}
/**
* 多个sheet页的数据链式写入(失败了会返回一个有部分数据的Excel)
* ExcelUtil.writeWithSheets(response, exportFileName)
* .writeModel(ExcelModel.class, excelModelList, "sheetName1")
* .write(headData, data,"sheetName2")
* .finish();
* @param response
* @param exportFileName 导出的文件名称
*/
public static EasyExcelWriterFactory writeWithSheetsWeb(HttpServletResponse response, String exportFileName) throws IOException{
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode(exportFileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(response.getOutputStream());
return excelWriter;
}
}
二、DefaultExcelListener
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Author: ww
* Datetime: 2020\8\12 0012
* Description: excel读取监听器
*/
@Slf4j
public class DefaultExcelListener<T> extends AnalysisEventListener<T> {
private final List<T> rows = new ArrayList();
/**
* 读取excel数据前操作(只有不读取表头数据时才会触发此方法)
*/
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
log.info("======================================================");
log.info("解析第一行数据:{}"+ JSON.toJSONString(headMap));
log.info("======================================================");
}
/**
* 读取excel数据操作
* @param object
* @param context
*/
@Override
public void invoke(T object, AnalysisContext context) {
rows.add(object);
log.info("list容量"+rows.size()+"---"+object);
/** 数据量不是特别大,可以不需要打开
// 实际数据量比较大时,rows里的数据可以存到一定量之后进行批量处理(比如存到数据库),
// 然后清空列表,以防止内存占用过多造成OOM
if(rows.size() >= 500){
log.info("存入数据库ing");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
rows.clear();
}
*/
}
/**
* 读取完excel数据后的操作
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("成功读取【"+ rows.size()+"】条数据");
}
/**
* 在读取excel异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
*/
@Override
public void onException(Exception exception, AnalysisContext context) {
log.error("解析失败,但是继续解析下一行:{}", exception.getMessage());
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
log.error("第{}行,第{}列解析异常,数据为:{}", excelDataConvertException.getRowIndex(),
excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
}
}
/**
* @return 返回读取excel总数据
*/
public List<T> getRows() {
return rows;
}
}
三、EasyExcelWriterFactory
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import java.io.File;
import java.io.OutputStream;
import java.util.List;
/**
* Author: ww
* Datetime: 2020\8\12 0012
* Description: 链式添加sheet表
*/
public class EasyExcelWriterFactory {
private int sheetNo = 0;
private ExcelWriter excelWriter = null;
public EasyExcelWriterFactory(OutputStream outputStream) {
excelWriter = EasyExcel.write(outputStream).build();
}
public EasyExcelWriterFactory(File file) {
excelWriter = EasyExcel.write(file).build();
}
public EasyExcelWriterFactory(String filePath) {
excelWriter = EasyExcel.write(filePath).build();
}
/**
* 链式模板表头写入
* @param headClazz 表头格式
* @param data 数据 List<ExcelModel> 或者List<List<Object>>
* @return
*/
public EasyExcelWriterFactory writeModel(Class headClazz, List data, String sheetName){
excelWriter.write(data, EasyExcel.writerSheet(this.sheetNo++, sheetName).head(headClazz).build());
return this;
}
/**
* 链式自定义表头写入
* @param head
* @param data 数据 List<ExcelModel> 或者List<List<Object>>
* @param sheetName
* @return
*/
public EasyExcelWriterFactory write(List<List<String>> head, List data, String sheetName){
excelWriter.write(data, EasyExcel.writerSheet(this.sheetNo++, sheetName).head(head).build());
return this;
}
/**
* 使用此类结束后,一定要关闭流
*/
public void finish() {
excelWriter.finish();
}
}
测试代码
注:为方便演示,就拿参数为文件路径的方法演示
将测试实体类导入项目
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Author: ww
* Datetime: 2020\8\12 0012
* Description: 测试模型
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ScoreData {
@ExcelProperty(value = "学号", index = 0)
private int id;
@ExcelProperty(value = "年级", index = 1)
private String senior;
@ExcelProperty(value = "学生", index = 2)
private String name;
@ExcelProperty(value = "语文", index = 3)
private int chinaese;
@ExcelProperty(value = "英语", index = 4)
private int english;
@ExcelProperty(value = "数学", index = 5)
private int math;
@ExcelProperty(value = "综合科", index = 6)
private int comprehensive;
}
首先先通过测试方法导出生成一个Excel表数据,用来测试Excel的导入
@Test
public void test8(){
//生成用来测试导出读取excel数据的成绩汇总表
String fileName = UUID.randomUUID().toString();
// String path = "C:\\Users\\Administrator\\Desktop\\"+fileName+".xls"; //导出路径
String path = "C:\\Users\\Administrator\\Desktop\\成绩汇总表.xls"; //导出路径
List<ScoreData> senior1 = new ArrayList<>();
List<ScoreData> senior2 = new ArrayList<>();
List<ScoreData> senior3 = new ArrayList<>();
Random random = new Random();
//初始化成绩表数据
for(int i = 1;i<=1000;i++){
ScoreData score1 = new ScoreData(i,"高一","学生"+i,random.nextInt(100)+50,random.nextInt(100)+50,random.nextInt(130)+20,random.nextInt(200)+100);
ScoreData score2 = new ScoreData(i,"高二","学生"+i,random.nextInt(100)+50,random.nextInt(100)+50,random.nextInt(130)+20,random.nextInt(200)+100);
ScoreData score3 = new ScoreData(i,"高三","学生"+i,random.nextInt(100)+50,random.nextInt(100)+50,random.nextInt(130)+20,random.nextInt(200)+100);
senior1.add(score1);
senior2.add(score2);
senior3.add(score3);
}
//导出Excel,链式添加sheet(使用此方法前提要将上文提到的三个类到导入项目)
EasyExcelWriterFactory res = EasyExcelUtil.writeWithSheets(path)
.writeModel(ScoreData.class, senior1, "高一成绩表")
.writeModel(ScoreData.class, senior2, "高二成绩表")
.writeModel(ScoreData.class, senior3, "高三成绩表");
res.finish(); //关闭流,不然会报错
}
测试Excel的导入读取数据
** 读取Excel数据测试类(不关联实体类) **
/**
* Author: ww
* Datetime: 2020\8\12 0012
* Description:
*/
public class ExcelDemo {
private String filePath = "C:\\Users\\Administrator\\Desktop\\成绩汇总表.xls";
@Test
public void test1(){
//同步读取excel数据(无实体类模型)
//参数1:文件绝对路径 参数2:Excel的第几个sheet 0:第一个 参数3:从第几行开始读取 0:第一行
List<Map<Integer, String>> data = EasyExcelUtil.syncRead(filePath,0,0);
for(Iterator it = data.iterator(); it.hasNext();){
Map<Integer,String> obj = (Map<Integer, String>) it.next();
System.out.println(obj);
}
}
@Test
public void test2(){
//同步读取excel数据(无实体类模型)----读取excel表的高二成绩表数据,从第一行开始读取
//参数1:文件绝对路径 参数2:Excel的第几个sheet 0:第一个 参数3:从第几行开始读取 0:第一行
List<Map<Integer, String>> data = EasyExcelUtil.syncRead(filePath,1,0);
for(Iterator it = data.iterator(); it.hasNext();){
Map<Integer,String> obj = (Map<Integer, String>) it.next();
System.out.println(obj);
}
}
}
test1运行结果:
{0=学号, 1=年级, 2=学生, 3=语文, 4=英语, 5=数学, 6=综合科}
{0=1.0, 1=高一, 2=学生1, 3=134.0, 4=113.0, 5=46.0, 6=293.0}
{0=2.0, 1=高一, 2=学生2, 3=129.0, 4=73.0, 5=69.0, 6=256.0}
{0=3.0, 1=高一, 2=学生3, 3=119.0, 4=82.0, 5=129.0, 6=232.0}
{0=4.0, 1=高一, 2=学生4, 3=107.0, 4=85.0, 5=40.0, 6=273.0}
{0=5.0, 1=高一, 2=学生5, 3=132.0, 4=112.0, 5=75.0, 6=106.0}
{0=6.0, 1=高一, 2=学生6, 3=80.0, 4=52.0, 5=141.0, 6=260.0}
..............
测试读取Excel数据(将Excel数据关联实体类)
@Test
public void test3(){
//同步读取excel数据(实体类模型)----读取excel表的第二张sheet高二成绩表数据,从第一行开始读取
List<T> obj = EasyExcelUtil.syncReadModel(filePath, ScoreData.class,1,1);
Iterator<T> it = obj.iterator();
while(it.hasNext()){
System.out.println("TODO插入数据库"+it.next());
}
}
test3运行结果:
TODO插入数据库ScoreData(id=1, senior=高二, name=学生1, chinaese=85, english=142, math=50, comprehensive=168)
TODO插入数据库ScoreData(id=2, senior=高二, name=学生2, chinaese=90, english=72, math=48, comprehensive=178)
TODO插入数据库ScoreData(id=3, senior=高二, name=学生3, chinaese=141, english=121, math=48, comprehensive=227)
TODO插入数据库ScoreData(id=4, senior=高二, name=学生4, chinaese=134, english=127, math=130, comprehensive=171)
TODO插入数据库ScoreData(id=5, senior=高二, name=学生5, chinaese=149, english=52, math=103, comprehensive=294)
TODO插入数据库ScoreData(id=6, senior=高二, name=学生6, chinaese=127, english=130, math=24, comprehensive=106)
.......
** 测试异步导入读取Excel数据(关联实体类)涉及到监听器类 **
@Test
public void test4(){
//异步读取excel数据(无实体类模型)----读取excel表的第一张sheet高一成绩表数据,从第一行开始读取
EasyExcelUtil.asyncRead(filePath,new DefaultExcelListener<>(),0,1);
//异步读取的数据会在监听器类里面处理数据
}
@Test
public void test5(){
//异步读取excel数据(有实体类模型)----读取excel表的第一张sheet高一成绩表数据,从第一行开始读取
EasyExcelUtil.asyncReadModel(filePath,new DefaultExcelListener<>(),ScoreData.class,0,1);
//异步读取的数据会在监听器类里面处理数据
}
test4测试结果:
09:53:30.019 [main] INFO com.excellence.scm.excel.DefaultExcelListener - ======================================================
09:53:30.019 [main] INFO com.excellence.scm.excel.DefaultExcelListener - 解析第一行数据:{}{0:"学号",1:"年级",2:"学生",3:"语文",4:"英语",5:"数学",6:"综合科"}
09:53:30.019 [main] INFO com.excellence.scm.excel.DefaultExcelListener - ======================================================
09:53:30.024 [main] INFO com.excellence.scm.excel.DefaultExcelListener - list容量1---{0=1.0, 1=高一, 2=学生1, 3=134.0, 4=113.0, 5=46.0, 6=293.0}
09:53:30.025 [main] INFO com.excellence.scm.excel.DefaultExcelListener - list容量2---{0=2.0, 1=高一, 2=学生2, 3=129.0, 4=73.0, 5=69.0, 6=256.0}
...........
09:53:33.236 [main] INFO com.excellence.scm.excel.DefaultExcelListener - 成功读取【1000】条数据
**测试导出Excel **
@Test
public void test6(){
//导出Excel(模拟从数据库查询的数据)
String fileName = UUID.randomUUID().toString();
String path = "C:\\Users\\Administrator\\Desktop\\"+fileName+".xls"; //导出路径
List<ScoreData> scores = new ArrayList<>();
Random random = new Random();
for(int i = 0; i < 10; i++){
ScoreData score1 = new ScoreData(i,"高一","学生"+i,random.nextInt(100)+50,random.nextInt(100)+50,random.nextInt(130)+20,random.nextInt(200)+100);
scores.add(score1);
}
EasyExcelUtil.write(path,ScoreData.class,scores,0,"成绩表");
}
test6测试结果:
温馨提示:以上使用FilePath作为参数方便演示,实战中应用,可使用参数为File和InputStream的方法(根据需求来使用),常用的方法都已在EasyExcelUtil类里封装好,拿来即用,特殊需求可自行封装。