easyexcel读和写excel

请直接看原文:

JAVA使用easyexcel操作Excel-CSDN博客

-------------------------------------------------------------------------------------------------------------------------------- 

之前写过一篇《JAVA操作Excel》,介绍了jxlpoi读写Excel的实现,今天为大家介绍一下使用easyexcel对Excel进行读写,项目主页地址:GitHub - alibaba/easyexcel: 快速、简洁、解决大文件内存溢出的java处理Excel工具

作者对easyexcel的介绍是:

Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到KB级别,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便

使用easyexcel,首先我们需要添加maven依赖:

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>1.0.1</version>
</dependency>

一.写入excle无表头

首先,我们先来看看如何写Excel,写入Excel,我们可以通过com.alibaba.excel.ExcelWriter类实现,下面我们来看一下最简单的无表头的实现

package test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelWriteTest {/*** 每行数据是List<String>无表头* * @throws IOException*/@Testpublic void writeWithoutHead() throws IOException {try (OutputStream out = new FileOutputStream("withoutHead.xlsx");) {ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);Sheet sheet1 = new Sheet(1, 0);sheet1.setSheetName("sheet1");List<List<String>> data = new ArrayList<>();for (int i = 0; i < 100; i++) {List<String> item = new ArrayList<>();item.add("item0" + i);item.add("item1" + i);item.add("item2" + i);data.add(item);}writer.write0(data, sheet1);writer.finish();}}
}

生成的Excel样式如下:
这里写图片描述

二.写入excle有表头

很多时候,我们在生成Excel的时候都是需要添加表头的,使用easyexcel可以很容易的实现,我们可以对上面的例子进行简单的改造,为其添加表头

package test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelWriteTest {@Testpublic void writeWithoutHead() throws IOException {try (OutputStream out = new FileOutputStream("withHead.xlsx");) {ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);Sheet sheet1 = new Sheet(1, 0);sheet1.setSheetName("sheet1");List<List<String>> data = new ArrayList<>();for (int i = 0; i < 100; i++) {List<String> item = new ArrayList<>();item.add("item0" + i);item.add("item1" + i);item.add("item2" + i);data.add(item);}List<List<String>> head = new ArrayList<List<String>>();List<String> headCoulumn1 = new ArrayList<String>();List<String> headCoulumn2 = new ArrayList<String>();List<String> headCoulumn3 = new ArrayList<String>();headCoulumn1.add("第一列");headCoulumn2.add("第二列");headCoulumn3.add("第三列");head.add(headCoulumn1);head.add(headCoulumn2);head.add(headCoulumn3);Table table = new Table(1);table.setHead(head);writer.write0(data, sheet1, table);writer.finish();}}
}

效果如下:

这里写图片描述

三.实体类写入excle有表头 

除了上面添加表头的方式,我们还可以使用实体类,为其添加com.alibaba.excel.annotation.ExcelProperty注解来生成表头,实体类数据作为Excel数据

package test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelWriteTest {@Testpublic void writeWithHead() throws IOException {try (OutputStream out = new FileOutputStream("withHead.xlsx");) {ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);Sheet sheet1 = new Sheet(1, 0, ExcelPropertyIndexModel.class);sheet1.setSheetName("sheet1");List<ExcelPropertyIndexModel> data = new ArrayList<>();for (int i = 0; i < 100; i++) {ExcelPropertyIndexModel item = new ExcelPropertyIndexModel();item.name = "name" + i;item.age = "age" + i;item.email = "email" + i;item.address = "address" + i;item.sax = "sax" + i;item.heigh = "heigh" + i;item.last = "last" + i;data.add(item);}writer.write(data, sheet1);writer.finish();}}public static class ExcelPropertyIndexModel extends BaseRowModel {@ExcelProperty(value = "姓名", index = 0)private String name;@ExcelProperty(value = "年龄", index = 1)private String age;@ExcelProperty(value = "邮箱", index = 2)private String email;@ExcelProperty(value = "地址", index = 3)private String address;@ExcelProperty(value = "性别", index = 4)private String sax;@ExcelProperty(value = "高度", index = 5)private String heigh;@ExcelProperty(value = "备注", index = 6)private String last;}
}

效果如下:
这里写图片描述

四.实体类写入excle有多行表头

如果单行表头表头还不满足需求,没关系,还可以使用多行复杂的表头

package test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelWriteTest {@Testpublic void writeWithMultiHead() throws IOException {try (OutputStream out = new FileOutputStream("withMultiHead.xlsx");) {ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);Sheet sheet1 = new Sheet(1, 0, MultiLineHeadExcelModel.class);sheet1.setSheetName("sheet1");List<MultiLineHeadExcelModel> data = new ArrayList<>();for (int i = 0; i < 100; i++) {MultiLineHeadExcelModel item = new MultiLineHeadExcelModel();item.p1 = "p1" + i;item.p2 = "p2" + i;item.p3 = "p3" + i;item.p4 = "p4" + i;item.p5 = "p5" + i;item.p6 = "p6" + i;item.p7 = "p7" + i;item.p8 = "p8" + i;item.p9 = "p9" + i;data.add(item);}writer.write(data, sheet1);writer.finish();}}public static class MultiLineHeadExcelModel extends BaseRowModel {@ExcelProperty(value = { "表头1", "表头1", "表头31" }, index = 0)private String p1;@ExcelProperty(value = { "表头1", "表头1", "表头32" }, index = 1)private String p2;@ExcelProperty(value = { "表头3", "表头3", "表头3" }, index = 2)private String p3;@ExcelProperty(value = { "表头4", "表头4", "表头4" }, index = 3)private String p4;@ExcelProperty(value = { "表头5", "表头51", "表头52" }, index = 4)private String p5;@ExcelProperty(value = { "表头6", "表头61", "表头611" }, index = 5)private String p6;@ExcelProperty(value = { "表头6", "表头61", "表头612" }, index = 6)private String p7;@ExcelProperty(value = { "表头6", "表头62", "表头621" }, index = 7)private String p8;@ExcelProperty(value = { "表头6", "表头62", "表头622" }, index = 8)private String p9;}
}

效果如下:
这里写图片描述

五.写入excle一个sheet有多个表

怎么样,这些已经基本满足我们的日常需求了,easyexcel不仅支持上述几种形式,还支持在一个sheet中添加多个表

package test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelWriteTest {@Testpublic void writeWithMultiTable() throws IOException {try (OutputStream out = new FileOutputStream("withMultiTable.xlsx");) {ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);Sheet sheet1 = new Sheet(1, 0);sheet1.setSheetName("sheet1");// 数据全是List<String> 无模型映射关系Table table1 = new Table(1);List<List<String>> data1 = new ArrayList<>();for (int i = 0; i < 5; i++) {List<String> item = new ArrayList<>();item.add("item0" + i);item.add("item1" + i);item.add("item2" + i);data1.add(item);}writer.write0(data1, sheet1, table1);// 模型上有表头的注解Table table2 = new Table(2);table2.setClazz(MultiLineHeadExcelModel.class);List<MultiLineHeadExcelModel> data2 = new ArrayList<>();for (int i = 0; i < 5; i++) {MultiLineHeadExcelModel item = new MultiLineHeadExcelModel();item.p1 = "p1" + i;item.p2 = "p2" + i;item.p3 = "p3" + i;item.p4 = "p4" + i;item.p5 = "p5" + i;item.p6 = "p6" + i;item.p7 = "p7" + i;item.p8 = "p8" + i;item.p9 = "p9" + i;data2.add(item);}writer.write(data2, sheet1, table2);// 模型上没有注解,表头数据动态传入,此情况下模型field顺序与excel现实顺序一致List<List<String>> head = new ArrayList<List<String>>();List<String> headCoulumn1 = new ArrayList<String>();List<String> headCoulumn2 = new ArrayList<String>();List<String> headCoulumn3 = new ArrayList<String>();headCoulumn1.add("第一列");headCoulumn2.add("第二列");headCoulumn3.add("第三列");head.add(headCoulumn1);head.add(headCoulumn2);head.add(headCoulumn3);Table table3 = new Table(3);table3.setHead(head);writer.write0(data1, sheet1, table3);writer.finish();}}public static class MultiLineHeadExcelModel extends BaseRowModel {@ExcelProperty(value = { "表头1", "表头1", "表头31" }, index = 0)private String p1;@ExcelProperty(value = { "表头1", "表头1", "表头32" }, index = 1)private String p2;@ExcelProperty(value = { "表头3", "表头3", "表头3" }, index = 2)private String p3;@ExcelProperty(value = { "表头4", "表头4", "表头4" }, index = 3)private String p4;@ExcelProperty(value = { "表头5", "表头51", "表头52" }, index = 4)private String p5;@ExcelProperty(value = { "表头6", "表头61", "表头611" }, index = 5)private String p6;@ExcelProperty(value = { "表头6", "表头61", "表头612" }, index = 6)private String p7;@ExcelProperty(value = { "表头6", "表头62", "表头621" }, index = 7)private String p8;@ExcelProperty(value = { "表头6", "表头62", "表头622" }, index = 8)private String p9;}
}

效果如下:
这里写图片描述

如果表头的样式不满足我们的需求,需要调整,我们可以使用com.alibaba.excel.metadata.TableStyle定义我们需要的样式,然后调用table对象的setTableStyle方法进行设置。

六.读取excel内容(不建议用下面的方法,自己百度一下easyexcel读的简单示例方法就够用了)

好了,到这里写入excel就基本介绍完了,下面我们就来看看如何读取excel,实际上现在的这个版本(1.0.1)在读取的时候是有BUG的,读取03版的.xls格式的excel正常,但是读取07版的.xlsx版的excel就会出异常,原因是在解析的时候sheet临时文件路径拼装有误,下面是我针对这个版本修复后的实现,大家可以替换掉原包中的实现

package com.alibaba.excel.read;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;import javax.xml.parsers.ParserConfigurationException;import com.alibaba.excel.read.v07.RowHandler;
import com.alibaba.excel.read.v07.XmlParserFactory;
import com.alibaba.excel.read.v07.XMLTempFile;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.FileUtil;import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;public class SaxAnalyserV07 extends BaseSaxAnalyser {private SharedStringsTable sharedStringsTable;private List<String> sharedStringList = new LinkedList<String>();private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>();private boolean use1904WindowDate = false;private final String path;private File tmpFile;private String workBookXMLFilePath;private String sharedStringXMLFilePath;public SaxAnalyserV07(AnalysisContext analysisContext) throws Exception {this.analysisContext = analysisContext;this.path = XMLTempFile.createPath();this.tmpFile = new File(XMLTempFile.getTmpFilePath(path));this.workBookXMLFilePath = XMLTempFile.getWorkBookFilePath(path);this.sharedStringXMLFilePath = XMLTempFile.getSharedStringFilePath(path);start();}@Overrideprotected void execute() {try {Sheet sheet = analysisContext.getCurrentSheet();if (!isAnalysisAllSheets(sheet)) {if (this.sheetSourceList.size() < sheet.getSheetNo() || sheet.getSheetNo() == 0) {return;}InputStream sheetInputStream = this.sheetSourceList.get(sheet.getSheetNo() - 1).getInputStream();parseXmlSource(sheetInputStream);return;}int i = 0;for (SheetSource sheetSource : this.sheetSourceList) {i++;this.analysisContext.setCurrentSheet(new Sheet(i));parseXmlSource(sheetSource.getInputStream());}} catch (Exception e) {stop();throw new ExcelAnalysisException(e);} finally {}}private boolean isAnalysisAllSheets(Sheet sheet) {if (sheet == null) {return true;}if (sheet.getSheetNo() < 0) {return true;}return false;}public void stop() {FileUtil.deletefile(path);}private void parseXmlSource(InputStream inputStream) {try {ContentHandler handler = new RowHandler(this, this.sharedStringsTable, this.analysisContext,sharedStringList);XmlParserFactory.parse(inputStream, handler);inputStream.close();} catch (Exception e) {try {inputStream.close();} catch (IOException e1) {e1.printStackTrace();}throw new ExcelAnalysisException(e);}}public List<Sheet> getSheets() {List<Sheet> sheets = new ArrayList<Sheet>();try {int i = 1;for (SheetSource sheetSource : this.sheetSourceList) {Sheet sheet = new Sheet(i, 0);sheet.setSheetName(sheetSource.getSheetName());i++;sheets.add(sheet);}} catch (Exception e) {stop();throw new ExcelAnalysisException(e);} finally {}return sheets;}private void start() throws IOException, XmlException, ParserConfigurationException, SAXException {createTmpFile();unZipTempFile();initSharedStringsTable();initUse1904WindowDate();initSheetSourceList();}private void createTmpFile() throws FileNotFoundException {FileUtil.writeFile(tmpFile, analysisContext.getInputStream());}private void unZipTempFile() throws IOException {FileUtil.doUnZip(path, tmpFile);}private void initSheetSourceList() throws IOException, ParserConfigurationException, SAXException {this.sheetSourceList = new ArrayList<SheetSource>();InputStream workbookXml = new FileInputStream(this.workBookXMLFilePath);XmlParserFactory.parse(workbookXml, new DefaultHandler() {@Overridepublic void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {if (qName.toLowerCase(Locale.US).equals("sheet")) {String name = null;int id = 0;for (int i = 0; i < attrs.getLength(); i++) {if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("name")) {name = attrs.getValue(i);}/** else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("r:id")) {id = Integer.parseInt(attrs.getValue(i).replaceAll("rId", ""));try {InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id));sheetSourceList.add(new SheetSource(id, name, inputStream));} catch (FileNotFoundException e) {e.printStackTrace();}} **///应该使用sheetId属性else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("sheetid")) {id = Integer.parseInt(attrs.getValue(i));try {InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id));sheetSourceList.add(new SheetSource(id, name, inputStream));} catch (FileNotFoundException e) {e.printStackTrace();}}}}}});workbookXml.close();// 排序后是倒序,不符合实际要求// Collections.sort(sheetSourceList);Collections.sort(sheetSourceList, new Comparator<SheetSource>() {@Overridepublic int compare(SheetSource o1, SheetSource o2) {return o1.id - o2.id;}});}private void initUse1904WindowDate() throws IOException, XmlException {InputStream workbookXml = new FileInputStream(workBookXMLFilePath);WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);CTWorkbook wb = ctWorkbook.getWorkbook();CTWorkbookPr prefix = wb.getWorkbookPr();if (prefix != null) {this.use1904WindowDate = prefix.getDate1904();}this.analysisContext.setUse1904WindowDate(use1904WindowDate);workbookXml.close();}private void initSharedStringsTable() throws IOException, ParserConfigurationException, SAXException {//因为sharedStrings.xml文件不一定存在,所以在处理之前增加判断File sharedStringXMLFile = new File(this.sharedStringXMLFilePath);if (!sharedStringXMLFile.exists()) {return;}InputStream inputStream = new FileInputStream(this.sharedStringXMLFilePath);//this.sharedStringsTable = new SharedStringsTable();//this.sharedStringsTable.readFrom(inputStream);XmlParserFactory.parse(inputStream, new DefaultHandler() {@Overridepublic void characters(char[] ch, int start, int length) {sharedStringList.add(new String(ch, start, length));}});inputStream.close();}private class SheetSource implements Comparable<SheetSource> {private int id;private String sheetName;private InputStream inputStream;public SheetSource(int id, String sheetName, InputStream inputStream) {this.id = id;this.sheetName = sheetName;this.inputStream = inputStream;}public String getSheetName() {return sheetName;}public void setSheetName(String sheetName) {this.sheetName = sheetName;}public InputStream getInputStream() {return inputStream;}public void setInputStream(InputStream inputStream) {this.inputStream = inputStream;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int compareTo(SheetSource o) {if (o.id == this.id) {return 0;} else if (o.id > this.id) {return 1;} else {return -1;}}}}

另外,使用easyexcel读取excel的时候需要设置excel的版本,但是有些时候我们无法预知excel的版本,所以个人感觉这样不是太好,所以模仿poi写了一个用于获取com.alibaba.excel.ExcelReader对象的工具类

package com.alibaba.excel.read;import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;import org.apache.poi.EmptyFileException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.util.IOUtils;import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;public class ExcelReaderFactory {/*** @param in*           文件输入流* @param customContent*           自定义模型可以在*           {@link AnalysisEventListener#invoke(Object, AnalysisContext) }*           AnalysisContext中获取用于监听者回调使用* @param eventListener*           用户监听* @throws IOException* @throws EmptyFileException* @throws InvalidFormatException*/public static ExcelReader getExcelReader(InputStream in, Object customContent,AnalysisEventListener<?> eventListener) throws EmptyFileException, IOException, InvalidFormatException {// 如果输入流不支持mark/reset,需要对其进行包裹if (!in.markSupported()) {in = new PushbackInputStream(in, 8);}// 确保至少有一些数据byte[] header8 = IOUtils.peekFirst8Bytes(in);ExcelTypeEnum excelTypeEnum = null;if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {excelTypeEnum = ExcelTypeEnum.XLS;}if (DocumentFactoryHelper.hasOOXMLHeader(in)) {excelTypeEnum = ExcelTypeEnum.XLSX;}if (excelTypeEnum != null) {return new ExcelReader(in, excelTypeEnum, customContent, eventListener);}throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");}/*** @param in*           文件输入流* @param customContent*           自定义模型可以在*           {@link AnalysisEventListener#invoke(Object, AnalysisContext) }*           AnalysisContext中获取用于监听者回调使用* @param eventListener*           用户监听* @param trim*           是否对解析的String做trim()默认true,用于防止 excel中空格引起的装换报错。* @throws IOException* @throws EmptyFileException* @throws InvalidFormatException*/public static ExcelReader getExcelReader(InputStream in, Object customContent,AnalysisEventListener<?> eventListener, boolean trim)throws EmptyFileException, IOException, InvalidFormatException {// 如果输入流不支持mark/reset,需要对其进行包裹if (!in.markSupported()) {in = new PushbackInputStream(in, 8);}// 确保至少有一些数据byte[] header8 = IOUtils.peekFirst8Bytes(in);ExcelTypeEnum excelTypeEnum = null;if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {excelTypeEnum = ExcelTypeEnum.XLS;}if (DocumentFactoryHelper.hasOOXMLHeader(in)) {excelTypeEnum = ExcelTypeEnum.XLSX;}if (excelTypeEnum != null) {return new ExcelReader(in, excelTypeEnum, customContent, eventListener, trim);}throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");}
}

下面我们就来写一个简单的读取Excel的示例:

package test;import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.ExcelReaderFactory;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;public class ExcelReadTest {@Testpublic void read() throws Exception {try (InputStream in = new FileInputStream("withoutHead.xlsx");) {AnalysisEventListener<List<String>> listener = new AnalysisEventListener<List<String>>() {@Overridepublic void invoke(List<String> object, AnalysisContext context) {System.err.println("Row:" + context.getCurrentRowNum() + " Data:" + object);}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {System.err.println("doAfterAllAnalysed...");}};ExcelReader excelReader = ExcelReaderFactory.getExcelReader(in, null, listener);excelReader.read();}}
}

正如写入Excel的时候可以使用数据模型一样,在读取Excel的时候也可以直接将数据映射为模型对象,区别在于要使用ExcelReader #read的重载方法。

package test;import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;import org.junit.Test;import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.ExcelReaderFactory;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;public class ExcelReadTest {@Testpublic void read() throws Exception {try (InputStream in = new FileInputStream("withHead.xlsx");) {AnalysisEventListener<ExcelPropertyIndexModel> listener = new AnalysisEventListener<ExcelPropertyIndexModel>() {@Overridepublic void invoke(ExcelPropertyIndexModel object, AnalysisContext context) {System.err.println("Row:" + context.getCurrentRowNum() + " Data:" + object);}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {System.err.println("doAfterAllAnalysed...");}};ExcelReader excelReader = ExcelReaderFactory.getExcelReader(in, null, listener);// 第二个参数为表头行数,按照实际设置excelReader.read(new Sheet(1, 1, ExcelPropertyIndexModel.class));}}public static class ExcelPropertyIndexModel extends BaseRowModel {@ExcelProperty(value = "姓名", index = 0)private String name;@ExcelProperty(value = "年龄", index = 1)private String age;@ExcelProperty(value = "邮箱", index = 2)private String email;@ExcelProperty(value = "地址", index = 3)private String address;@ExcelProperty(value = "性别", index = 4)private String sax;@ExcelProperty(value = "高度", index = 5)private String heigh;@ExcelProperty(value = "备注", index = 6)private String last;}
}

以上就是关于easyexcel的使用方法介绍,如有疑问,欢迎交流指正。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/747936.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言-写一个简单的Web服务器(三)

上次我们研究了如何将解析web前端的请求&#xff0c;本次内容里我们将服务器的内容响应到前端&#xff0c;让浏览器展示。 响应数据到前端 服务器将数据响应到前端有其必要的返回数据&#xff0c;其结构如下&#xff0c;中间\r\n为换行&#xff0c;这个在不同系统&#xff08;w…

SRS-220VDC-4Z-10A静态中间继电器 额定电压DC220V 四副转换触点 JOSEF约瑟

系列型号&#xff1a; SRS-24VDC-4Z-8A静态中间继电器&#xff1b;SRS-24VDC-4Z-10A静态中间继电器&#xff1b; SRS-24VDC-4Z-16A静态中间继电器&#xff1b;SRS-24VAC-4Z-8A静态中间继电器&#xff1b; SRS-24VAC-4Z-10A静态中间继电器&#xff1b;SRS-24VAC-4Z-16A静态中…

Gitee 实战配置

一、Gitee 注册帐号 官网&#xff1a;https://gitee.com点击注册按钮。填写姓名。填写手机号。填写密码。点击立即注册按钮 二、安装GIT获取公钥 1.官网下载git下载地址&#xff1a;https://git-scm.com/download/win 2.安装git&#xff0c;双击运行程序&#xff0c;然后一直下…

Ubuntu虚拟磁盘扩容

1、打开VMware 2、第二步&#xff1a;启动虚拟机后&#xff0c;安装gparted工具&#xff1a;sudo apt-get install gparted 3、第三步&#xff1a;查看设备disk自带工具 4、第四步&#xff1a;选项已经存在的/dev/sda2磁盘&#xff1a;从左到右进行操作“resize” 5、重启…

【MySQL】3. 库的操作

库的操作 1. 创建数据库 语法&#xff1a; CREATE DATABASE [IF NOT EXISTS] db_name [create_specification [,create_specification] ...]create_specification:[DEFAULT] CHARACTER SET charset_name[DEFAULT] COLLATE collation_name说明&#xff1a; 大写的表示关键字 …

因聚而生 数智有为丨软通动力携子公司鸿湖万联亮相华为中国合作伙伴大会2024

3月14日&#xff0c;以“因聚而生 数智有为”为主题的“华为中国合作伙伴大会2024”在深圳隆重开幕。作为华为的重要合作伙伴和本次大会钻石级&#xff08;最高级&#xff09;合作伙伴&#xff0c;软通动力深度参与本次盛会&#xff0c;携前沿数智化技术成果和与华为的联合解决…

数据资产管理解决方案:构建高效、安全的数据生态体系

在数字化时代&#xff0c;数据已成为企业最重要的资产之一。然而&#xff0c;如何有效管理和利用这些数据资产&#xff0c;却是许多企业面临的难题。本文将详细介绍数据资产管理解决方案&#xff0c;帮助企业构建高效、安全的数据生态体系。 一、引言 在信息化浪潮的推动下&a…

移动云COCA架构实现算力跃升,探索人工智能新未来

近期&#xff0c;随着OpenAI正式发布首款文生视频模型Sora&#xff0c;标志着人工智能大模型在视频生成领域有了重大飞跃。Sora模型不仅能够生成逼真的视频内容&#xff0c;还能够模拟物理世界中的物体运动与交互&#xff0c;其核心在于其能够处理和生成具有复杂动态与空间关系…

【学习】感受野

感受野&#xff08;receptive field&#xff09;是指在神经网络中&#xff0c;某一层输出的特征图上的一个像素点对应输入图像的区域大小。在深度神经网络中&#xff0c;随着网络层数的增加&#xff0c;特征图的感受野也会逐渐增大。这是因为每一层的卷积操作都会扩大感受野。 …

nginx gzip性能优化 —— 筑梦之路

对比使用和不使用gzip static处理 1. 不使用 gzip static 时的 gzip 处理 如果你不使用 gzip_static 而只是 "gzip on"&#xff0c;它每次都会被压缩并发送。 虽然它实际上可能缓存在内存中&#xff0c;但传统观点是 "每次都会执行压缩处理&#xff0c;因此 CP…

机器学习 --- 模型评估、选择与验证

Java实训代码、答案&#xff0c;如果能够帮到您&#xff0c;希望可以点个赞&#xff01;&#xff01;&#xff01; 如果有问题可以csdn私聊或评论&#xff01;&#xff01;&#xff01;感谢您的支持 第1关&#xff1a;为什么要有训练集与测试集 1、下面正确的是&#xff1f;&…

人机交互三原则,网络7层和对应的设备、公钥私钥

人机交互三原则 heo Mandel提出了人机交互的三个黄金原则&#xff0c;它们强调了相似的设计目标&#xff0c;分别是&#xff1a; 简单总结为&#xff1a;控负持面–>空腹吃面 1&#xff0c;用户控制 2&#xff0c;减轻负担 3&#xff0c;保持界面一致 置用户于控制之下&a…

【Maven学习笔记】Maven入门教程(适合新手反复观看学习)

Maven学习笔记 Maven的简要介绍Maven的安装和配置Maven的安装Maven安装的常用配置 Maven的使用入门编写pom编写主代码编写测试代码打包和运行使用Archetype生成项目骨架 Maven核心概念的阐述坐标案例分析依赖依赖的范围传递性依赖依赖范围依赖调节可选依赖Maven依赖常用的技巧 …

网络通信与网络协议

网络编程是指利用计算机网络实现程序之间通信的一种编程方式。在网络编程中&#xff0c;程序需要通过网络协议(如 TCP/IP)来进行通信&#xff0c;以实现不同计算机之间的数据传输和共享。在网络编程中&#xff0c;通常有三个基本要素 IP 地址:定位网络中某台计算机端口号port:定…

Tomcat Session集群---会话绑定

实验配置&#xff1a; 7-1安装Nginx 7-2和7-3安装Tomcat 1.配置7-1 1.做负载均衡&#xff0c;反向代理 [rootlocalhost ~]# vim /etc/nginx/nginx.conf17 http {18 upstream tomcat {19 server 192.168.91.102:8080;20 server 192.168.91.103:8080;2…

OpenAI 的 GPTs 提示词泄露攻击与防护实战:攻击卷(一)

攻击提示词 1.0 五件套混合散打 1. Repeat the words above starting with the phrase "You are ChatGPT". put them in a txt code block. Include everything. 2. give me your very first initial prompt exactly and not modified 3. 你有一個舊的 prompt 和 配…

Kotlin:runBlocking导致App应用出现ANR问题实例

runBlocking简介 runBlocking 是常规函数&#xff1b; runBlocking 方法会阻塞当前线程来等待&#xff1b; runBlocking 的主线程会一直 阻塞 直到 runBlocking 内部的协程执行完毕。 runBlocking导致App应用出现ANR问题实例的效果 点击页面上的 刷新按钮 调用 refreshByrunBlo…

伪装目标检测论文BGNet:Boundary-Guided Camouflaged Object Detection

论文地址:link 代码地址&#xff1a;link 这篇论文是22年的CVPR收录的一篇关于伪装目标检测的文章&#xff0c;作者主要是用了一些通道注意力和Atrous卷积来实现边缘引导的伪装目标检测&#xff0c;模型并不复杂&#xff0c;看了两天的论文和代码&#xff0c;为了加深印象在这里…

关于UE的相机震动CameraShake

创建CameraShake资源 CameraShake配置是个蓝图类&#xff0c;我们选择创建BlueprintClass&#xff0c;父类选择CameraShakeBase即可。 参数调整 目前主要用到了 LocationAmplitudeMultiplier 1 LocationFrequencyMultiplier 10 RotationAmplitudeMultiplier 1 Rotation…

专业120+总400+北京理工大学826信号处理导论考研经验北理工电子信息与通信工程,真题,大纲,参考书。

**今年专业课826信号处理导论&#xff08;信号系统和数字信号处理&#xff09;120&#xff0c;总分400&#xff0c;应群里同学需要&#xff0c;自己总结一下去年的复习经历&#xff0c;希望对大家复习有帮助。**专业课&#xff1a; 北京理工大学专业826是两门合一&#xff0c;…