Apache POI和EasyExcel学习

easyExcel

easyExcel 官网地址:https://www.yuque.com/easyexcel/doc/easyexcel

EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单,节省内存著称

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。 github地址:https://github.com/alibaba/easyexcel

对比:

  • POI:读完再写,如果文件内容过大,容易OOM
  • easy:一行一行读取

一、POI-Excel读

idea创建新项目

导jar包或者依赖

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><!--xls(03)--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><!--xlsx(07)--><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
package com.lxf.excel;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ReadExcel {public static void main(String[] args) {//读取excel文件String path = "C:\\Users\\Desktop\\Mytest.xlsx";InputStream is = null;try {is = new FileInputStream(path);//创建一个Workbook对象读取xlsx文件Workbook workbook = new XSSFWorkbook(is);//读取sheet//获取sheet的数量int numberOfSheets = workbook.getNumberOfSheets();System.out.println("sheet的数量是:"+numberOfSheets);//获取对应的sheet表//直接通过工作表的名称获取对应的工作表对象//如果获取的名称不存在,返回nullSheet sheet1 = workbook.getSheet("sheet1");//通过工作表获取行//获取sheet1中的所有的行(物理的行数:只有写了内容的行数才会算)int numberOfRows = sheet1.getPhysicalNumberOfRows();//DataFormatter formatter = new DataFormatter();    System.out.println("行数:"+numberOfRows);for (int i = 0; i < numberOfRows; i++) {Row row = sheet1.getRow(i);//通过每一行获取所有的列//获取列数int numberOfCells = row.getPhysicalNumberOfCells();System.out.println("第"+(i+1)+"行的列数:"+numberOfCells);//获取每一列的内容for (int j = 0; j < numberOfCells; j++) {//获取每一列的cell对象Cell cell = row.getCell(j);//获取坐标对象。//CellReference reference = new CellReference(row.getRowNum(), cell.getColumnIndex());//获取所有的内容
//                  String value = cell.getStringCellValue();
//                  System.out.println("value="+value);//获取每一个数据的类型try {//将所有的类型都转化成字符串//System.out.println("value-->"+reference.formatAsString()+":"+formatter.formatCellValue(cell));if (cell.getCellComment() != null) {System.out.println(cell.getCellComment().getAuthor());System.out.println(cell.getCellComment().getString());}switch (cell.getCellType()) {case Cell.CELL_TYPE_BLANK:System.out.println("空白");break;case Cell.CELL_TYPE_BOOLEAN:System.out.println("布尔类型:"+cell.getBooleanCellValue());break;case Cell.CELL_TYPE_ERROR:System.out.println("警告类型:"+cell.getErrorCellValue());break;case Cell.CELL_TYPE_FORMULA:System.out.println("公式类型:"+cell.getCellFormula());break;case Cell.CELL_TYPE_NUMERIC:if (DateUtil.isCellDateFormatted(cell)) {//判断是否是时间类型System.out.println("时间类型:"+cell.getDateCellValue());} else {System.out.println("数字类型:"+cell.getNumericCellValue());}break;case Cell.CELL_TYPE_STRING:System.out.println("字符串型:"+cell.getStringCellValue());break;default:System.out.println("其他类型");break;}
//                      System.out.println("第"+(j+1)+"列:"+cell.getCellType());} catch (Exception e) {System.out.println("第"+(j+1)+"列:null");}
//                  Cell.CELL_TYPE_BLANK --> 空白
//                  Cell.CELL_TYPE_BOOLEAN --> 布尔类型
//                  Cell.CELL_TYPE_ERROR --> 警告
//                  Cell.CELL_TYPE_FORMULA --> 函数
//                  Cell.CELL_TYPE_NUMERIC --> 数字
//                  Cell.CELL_TYPE_STRING --> 字符串}System.out.println("----------------------------");}System.out.println("Cell.CELL_TYPE_BLANK-->"+Cell.CELL_TYPE_BLANK);System.out.println("Cell.CELL_TYPE_BOOLEAN-->"+Cell.CELL_TYPE_BOOLEAN);System.out.println("Cell.CELL_TYPE_ERROR-->"+Cell.CELL_TYPE_ERROR);System.out.println("Cell.CELL_TYPE_FORMULA-->"+Cell.CELL_TYPE_FORMULA);System.out.println("Cell.CELL_TYPE_NUMERIC-->"+Cell.CELL_TYPE_NUMERIC);System.out.println("Cell.CELL_TYPE_STRING-->"+Cell.CELL_TYPE_STRING);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

数据批量导入!

1.大文件写HSSF

缺点:最多只能处理65535行,否则会抛出异常

优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘。速度快

2.大文件写XSSF

缺点:写数据时速度非常快,非常耗内存,也会发生内存溢出,如100万条

优点:可以写较大的数据量,如20万条

3.实际应用(将excel文件的内容写入数据库):
package com.zking.excel;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import org.apache.commons.dbutils.QueryRunner;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.zking.dao.DBPool;
import com.zking.entity.Product;/***    导入数据*/
public class ImportExcel {public static List<Product> importData(String filePath) throws IOException{if (filePath == null)return null;//判断文件是否存在File file = new File(filePath);if (file == null || !file.exists())throw new FileNotFoundException("文件路径不存在!!!");//创建一个工作簿Workbook workbook = null;if (filePath.endsWith("xlsx"))workbook = new XSSFWorkbook(new FileInputStream(file));else if (filePath.endsWith("xls"))workbook = new HSSFWorkbook(new FileInputStream(file));else return null;//不是excel文件//创建一个集合,存储获取的数据List<Product> products = new ArrayList<Product>();//获取excel的第一个sheetSheet sheet = workbook.getSheetAt(0);//获取每一行。从第二行开始。for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {Row row = sheet.getRow(i);//每一行创建一个对象Product product = new Product();product.setPro_name(row.getCell(0).getStringCellValue());product.setPro_price(row.getCell(1).getNumericCellValue());product.setPro_stock((int)(row.getCell(2).getNumericCellValue()));product.setPro_coverPic(row.getCell(3).getStringCellValue());products.add(product);}return products;}//将list集合的数据转化成二维数组public static Object[][]  listToArray(List<Product> products){Object[][] objs = new Object[products.size()][4];for (int i = 0; i < products.size(); i++) {objs[i][0] = products.get(i).getPro_name();objs[i][1] = products.get(i).getPro_price();objs[i][2] = products.get(i).getPro_stock();objs[i][3] = products.get(i).getPro_coverPic();}return objs;}public static void main(String[] args) {try {List<Product> products = ImportExcel.importData("D:\\Product\\商品数据 - 增加.xlsx");QueryRunner runner = new QueryRunner(DBPool.getInstance().getDataSource());String sql = "insert into product values(null,?,?,?,?)";int[] count = runner.batch(sql, listToArray(products));int sum = 0;for (int i = 0; i < count.length; i++) {sum += count[i];}System.out.println("成功导入"+sum+"条数据!!!");} catch (IOException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}}
4.计算公式
package com.lxf.excel;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ReadExcel {public static void main(String[] args) {//读取excel文件String path = "C:\\Users\\Desktop\\Mytest.xlsx";InputStream is = null;try {is = new FileInputStream(path);//创建一个Workbook对象读取xlsx文件Workbook workbook = new XSSFWorkbook(is);//获取对应的sheet表Sheet sheet1 = workbook.getSheet("sheet1");Row row=sheet1.getRow(4);Cell cell=row.getCell(0);//拿到计算公式FormulaEvaluator formulaEvaluator=new HSSFFormulaEvaluator((XSSFWorkbook) workbook);//输出单元格的内容int celltype=cell.getCellType();switch(celltype){case Cell.CELL_TYPE_FORMULA://公式类型String formula=cell.getCellFormula();System.out.printIn(formula);//计算CellValue evaluate=FormulaEvaluator.evaluate(cell);String cellValue=evaluate.formatAsString();System.out.printIn(cellValue);break;}formulaEvaluator}}
}

二、POI-Excel写

package com.zking.excel;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class CreateExcel {public static void main(String[] args) {//为什么要去操作excel//a.打卡机-->excel的文件//b.要把excel数据导入到数据库//c.把数据库的数据到处到excel表//d.使用Java创建一个excel文件//创建excel工作簿的对象//操作excel表格的对象
//      HSSFWorkbook 操作xls文件 97~2003版本的office
//      XSSFWorkbook 操作xlsx文件 2003版本之后新出的excel格式
//      Workbook//正式使用代码创建excel文件//1.创建一个Workbook工作簿对象(相当于整个excel文件的窗口)//Workbook workbook = new HSSFWorkbook();Workbook workbook = new XSSFWorkbook();//2.通过workbook对象,创建一个sheet。不传参数就默认自动命名sheetnSheet sheet = workbook.createSheet("商品数据");//3.通过sheet对象,创建第一行Row row1 = sheet.createRow(0);//3.1 通过第一行创建第一列Cell cell1_1 = row1.createCell(0);//3.2 通过第一列设置数据cell1_1.setCellValue("编号");//第二列Cell cell1_2 = row1.createCell(1);//3.2 通过第一列设置数据cell1_2.setCellValue("商品名称");//第三列Cell cell1_3 = row1.createCell(2);//3.2 通过第一列设置数据cell1_3.setCellValue("商品价格");//第三列Cell cell1_4 = row1.createCell(3);//3.2 通过第一列设置数据cell1_4.setCellValue("商品库存");//第二行Row row2 = sheet.createRow(1);row2.createCell(0).setCellValue(1);row2.createCell(1).setCellValue("连衣裙,超漂亮");row2.createCell(2).setCellValue(999.00);row2.createCell(3).setCellValue(1000);//第三行Row row3 = sheet.createRow(2);row3.createCell(0).setCellValue(2);row3.createCell(1).setCellValue("小猪佩奇玩偶");row3.createCell(2).setCellValue(8888.88);row3.createCell(3).setCellValue(222);//4.通过workbook将excel文件写入到磁盘中String path = "d:\\productData";File file = new File(path);if (file == null || !file.exists()) {file.mkdirs();}path += "\\商品数据.xlsx";try {OutputStream out = new FileOutputStream(path);workbook.write(out);System.out.println("文件创建成功!!!");} catch (IOException e) {e.printStackTrace();}}
}
实际应用(将数据库的内容写入excel文件):
package com.zking.excel;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.zking.dao.DBPool;
import com.zking.entity.Product;
import com.zking.entity.ProductPics;
import com.zking.entity.User;/***   导出excel文件*/
public class ExportExcel {// 自适应宽度(中文支持)public static void setSizeColumn(Sheet sheet, int size) {for (int columnNum = 0; columnNum < size; columnNum++) {int columnWidth = sheet.getColumnWidth(columnNum) / 256;for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {Row currentRow;//当前行未被使用过if (sheet.getRow(rowNum) == null) {currentRow = sheet.createRow(rowNum);} else {currentRow = sheet.getRow(rowNum);}if (currentRow.getCell(columnNum) != null) {Cell currentCell = currentRow.getCell(columnNum);if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {int length = currentCell.getStringCellValue().getBytes().length;if (columnWidth < length) {columnWidth = length;}}}}sheet.setColumnWidth(columnNum, columnWidth * 256);}}/***  使用反射导出* @param objs* @param clas* @param path* @param fileName* @throws IOException*/public static <T> void exportObject(List<T> objs, Class<T> clas, String path, String fileName) throws Exception {//表头Field[] fields = clas.getDeclaredFields();String[] head = new String[fields.length];for (int i = 0; i < fields.length; i++) {head[i] = fields[i].getName();}//创建excel文件Workbook workbook = new XSSFWorkbook();CellStyle cellStyle = workbook.createCellStyle();cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);Sheet sheet = workbook.createSheet("商品数据");//创建第一行Row row1 = sheet.createRow(0);for (int i = 0; i < head.length; i++) {row1.createCell(i).setCellValue(head[i]);row1.getCell(i).setCellStyle(cellStyle);}//创建后面的行for (int i = 0; i < objs.size(); i++) {Row row = sheet.createRow(i+1);T t = objs.get(i);for (int j = 0; j < fields.length; j++) {//使用get方法去取String fieldName = fields[j].getName();String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);Method method = clas.getDeclaredMethod(methodName);//执行method的get方法Object obj = method.invoke(t);//设置值的时候,判断Cell cell = row.createCell(j);setCell(cell, obj);}//设置样式for (int j = 0; j < head.length; j++) {row.getCell(j).setCellStyle(cellStyle);}}//设置所有的列都自动适应宽高for (int i = 0; i < head.length; i++) {sheet.autoSizeColumn(i);}ExportExcel.setSizeColumn(sheet, head.length);//写入文件File file = new File(path);if (file == null || !file.exists())file.mkdirs();OutputStream out = new FileOutputStream(path + "\\" + fileName);workbook.write(out);}public static void setCell(Cell cell, Object obj) {if (obj == null) {cell.setCellValue("");return;}switch (obj.getClass().getSimpleName()) {//八种数据写全case "Integer":cell.setCellValue(Integer.parseInt(obj.toString()));break;case "String":cell.setCellValue(obj.toString());break;case "Double":cell.setCellValue(Double.parseDouble(obj.toString()));break;default://其他数据类型cell.setCellValue("");break;}}public static void export(List<Product> products, String path, String fileName) throws IOException {//表头String[] head = {"编号","商品名称","商品价格","商品库存","商品封面"};//创建excel文件Workbook workbook = new XSSFWorkbook();CellStyle cellStyle = workbook.createCellStyle();cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);Sheet sheet = workbook.createSheet("商品数据");//创建第一行Row row1 = sheet.createRow(0);for (int i = 0; i < head.length; i++) {row1.createCell(i).setCellValue(head[i]);row1.getCell(i).setCellStyle(cellStyle);}//创建后面的行for (int i = 0; i < products.size(); i++) {Row row = sheet.createRow(i+1);row.createCell(0).setCellValue(products.get(i).getId());row.createCell(1).setCellValue(products.get(i).getPro_name());row.createCell(2).setCellValue(products.get(i).getPro_price());row.createCell(3).setCellValue(products.get(i).getPro_stock());row.createCell(4).setCellValue(products.get(i).getPro_coverPic());//设置样式for (int j = 0; j < head.length; j++) {row.getCell(j).setCellStyle(cellStyle);}}//设置所有的列都自动适应宽高for (int i = 0; i < head.length; i++) {sheet.autoSizeColumn(i);}ExportExcel.setSizeColumn(sheet, head.length);//写入文件File file = new File(path);if (file == null || !file.exists())file.mkdirs();OutputStream out = new FileOutputStream(path + "\\" + fileName);workbook.write(out);}public static void main(String[] args) {QueryRunner runner = new QueryRunner(DBPool.getInstance().getDataSource());try {//把数据导出到excelString sql = "select * from lxf_user";List<User> users = runner.query(sql, new BeanListHandler<User>(User.class));ExportExcel.exportObject(users, User.class, "D:\\Product\\Excel", "用户数据 - 反射.xlsx");System.out.println("文件导出成功!!!");} catch (Exception e) {System.err.println("文件导出失败!"+e.getMessage());}                      }
}

三、EasyExcel的读写

3.1、导入依赖
 <!--alibaba的easyexcel--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>
3.2、EasyExcel-写

新建DemoData类:

package com.lxf;import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;import java.util.Date;@Data
public class DemoData {@ExcelProperty("字符串标题")private String string;@ExcelProperty("日期标题")private Date date;@ExcelProperty("数字标题")private Double doubleData;/*** 忽略这个字段*/@ExcelIgnoreprivate String ignore;
}

在resourece文件夹下新建log4j.properties文件:

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

新建测试类MyTest类:

package com.lxf;import com.alibaba.excel.EasyExcel;
import org.junit.Test;import java.util.ArrayList;
import java.util.Date;
import java.util.List;public class MyTest {//写出的目录String path="C:\\Users\\Administrator\\Desktop\\";private List<DemoData> data() {List<DemoData> list = new ArrayList<DemoData>();for (int i = 0; i < 10; i++) {DemoData data = new DemoData();data.setString("字符串" + i);data.setDate(new Date());data.setDoubleData(0.56);list.add(data);}return list;}//根据list写入excel@Testpublic void simpleWrite() {// 写法1String fileName = path + "EasyTest.xlsx";// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭// 如果这里想使用03 则 传入excelType参数即可EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());// 写法2// fileName = path + "EasyTest.xlsx";// // 这里 需要指定写用哪个class去写// ExcelWriter excelWriter = null;// try {//     excelWriter = EasyExcel.write(fileName, DemoData.class).build();//     WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();//     excelWriter.write(data(), writeSheet);// } finally {//     // 千万别忘记finish 会帮忙关闭流//     if (excelWriter != null) {//         excelWriter.finish();//     }// }}
}
3.3、EasyExcel-读

新建DemoDataListener类:

package com.lxf;import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.ArrayList;
import java.util.List;// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public class DemoDataListener extends AnalysisEventListener<DemoData> {private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);/*** 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收*/private static final int BATCH_COUNT = 5;List<DemoData> list = new ArrayList<DemoData>();/*** 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。*/private DemoDAO demoDAO;public DemoDataListener() {// 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数demoDAO = new DemoDAO();}/*** 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来** @param demoDAO*/public DemoDataListener(DemoDAO demoDAO) {this.demoDAO = demoDAO;}/*** 这个每一条数据解析都会来调用** @param data:类型*            one row value. Is is same as {@link AnalysisContext#readRowHolder()}* @param context 分析上下文*/@Overridepublic void invoke(DemoData data, AnalysisContext context) {LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));list.add(data);// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOMif (list.size() >= BATCH_COUNT) {saveData();//持久化逻辑// 存储完成清理 listlist.clear();}}/*** 所有数据解析完成了 都会来调用** @param context*/@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {// 这里也要保存数据,确保最后遗留的数据也存储到数据库saveData();LOGGER.info("所有数据解析完成!");}/*** 加上存储数据库*/private void saveData() {LOGGER.info("{}条数据,开始存储数据库!", list.size());demoDAO.save(list);LOGGER.info("存储数据库成功!");}
}

新建DemoDAO类(用于数据库转储,测试没用到可不写):

package com.lxf;import java.util.List;/*** 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。**/
public class DemoDAO {public void save(List<DemoData> list) {// 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入}
}

新建测试类MyTest类:

 package com.lxf;import com.alibaba.excel.EasyExcel;
import org.junit.Test;public class MyTest {//写出的目录String path="C:\\Users\\Administrator\\Desktop\\";@Testpublic void simpleRead() {// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去// 写法1:String fileName = path + "EasyTest.xlsx";// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();// 写法2:// fileName = path + "EasyTest.xlsx";// ExcelReader excelReader = null;// try {//     excelReader = EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).build();//     ReadSheet readSheet = EasyExcel.readSheet(0).build();//     excelReader.read(readSheet);// } finally {//     if (excelReader != null) {//         // 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的//         excelReader.finish();//     }// }}
}

Java操作excel(POI、EasyExcel)相关推荐

  1. java excel api 下载文件_Java-Excel Java操作Excel POI(Jakarta POI API) - 下载 - 搜珍网

    Java操作Excel/Jakarta POI API/data/Jakarta POI API.doc Java操作Excel/Jakarta POI API/jar/poi-3.0.2-FINAL ...

  2. Java操作Excel之EasyExcel、标题、背景色设置

    首先不管是学习或者是了解什么技术都要先去看下官方文档 https://alibaba-easyexcel.github.io/index.html 1.import maven depend(导入项目 ...

  3. Java 操作Excel POI

    对指定的单元格进行填充具体的值: public static boolean setValuebySheetRowColumn(Sheet OneSheet, int row, int column, ...

  4. Java操作excel工具easyExcel

    推荐阅读: https://blog.csdn.net/jiangjiandecsd/article/details/81115622 转载于:https://www.cnblogs.com/mxh- ...

  5. Java操作Excel三种方式POI、Hutool、EasyExcel

    Java操作Excel三种方式POI.Hutool.EasyExcel 1. Java操作Excel概述 1.1 Excel需求概述 1.2 Excel操作三种方式对比 2. ApachePOIExc ...

  6. java excel读取操作,Java 操作 Excel (读取Excel2003 2007,Poi兑现)

    Java 操作 Excel (读取Excel2003 2007,Poi实现) 一. Apache POI 简介( http://poi.apache.org/) 使用Java程序读写Microsoft ...

  7. Java操作Excel之POI:java读写excel文件以及打印设置

    Java操作Excel之POI:java读写excel文件以及打印设置 POI的jar包下载地址:http://poi.apache.org/download.html 注意:项目中导入poi 4.0 ...

  8. java insert row,POI ,Java 操作 Excel 实现行的插入(insert row)

    POI ,Java 操作 Excel 实现行的插入(insert row) 前几天,正在做一个项目,主要用 POI 来操作 Excel 其中,要使用一个,插入功能.主要是因为从数据库,返回结果集(数据 ...

  9. java操作excel

    使用Java操作excel可以使用两种方式: 关于表格导入导出,市面上比较知名的开源就是 Apache 的POI 和 阿里巴巴的 EasyExcel了.EasyExcel 也是对 POI 的改进和封装 ...

最新文章

  1. 微软公布Win10正式版功能对比表,哪个版本适合你?
  2. 【Android View绘制之旅】Layout过程
  3. QTP的那些事--终极项目脚本设计思路及其测试查询功能的一些实际项目体会
  4. Java调用webservice.asmx接口.
  5. authentication plugin caching_sha2
  6. openstack kvm 虚拟机磁盘差异衍生
  7. python软件打不开_ubuntu装python3.1.1之后出错,软件中心打不开,不能重装。尝试sudo apt-get -f install报error...
  8. 任务调度-java普通工程通过Timer实现
  9. Jenkins配置MSBuild时使用环境变量
  10. LeetCode之同构字符串
  11. Java基础6:代码块与代码加载顺序
  12. VEP视频文件怎么转换成普通视频文件mp4
  13. bind9 域名劫持_域名劫持会怎样?如何解决域名劫持
  14. 基于深度学习的语义分割
  15. 东半球最好的TV桌面开源项目
  16. 自己总结的html+css试题
  17. webService公共开放接口大全
  18. php微信公众号向指定客服发信息,微信公众号给用户发送一条消息 客服消息
  19. 开源OA办公平台搭建教程:O2OA+Arduino实现物联网应用(五)
  20. Warning: Class ‘com.xxx.xxx‘ not found in module ‘xxxx‘

热门文章

  1. 211机械本科毕业3年,从制造业跳槽互联网大数据开发,收割虾皮百度美团等offer...
  2. 从零开始学python编程之格式化符号
  3. http协议详解-摘抄
  4. MATLAB中产生周期方波信号
  5. 这个python是干嘛的啊-python干嘛用
  6. 盘点 | 2021年十大网络安全漏洞
  7. 微信冷知识|那些朋友圈文字被折叠的原因所在
  8. 实验 Pi-FM-RDS 使用 Raspberry Pi 的 FM-RDS 发射器
  9. 计算机英语教学教案模板,英语教学教案模板
  10. 2022深圳杯C题讲解