easyexcel导入导出操作

package yinzs;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.collections4.ListUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelreadTest {
    String PATH="D:\\wenhao\\yinzs-pol\\";

    /**
     * 文件写入
     * @throws IOException
     */
    @Test
    public  void  testWrite03() throws IOException {

        FileInputStream fileInputStream = new FileInputStream(PATH+"洲哥学习导入导出操作.xls");

        //1.获取一个工作薄 使用excel操作它都能设置
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        //2.获取一个工作表
        Sheet sheetAt = workbook.getSheetAt(0);
        //3.获取一个列
        Row row = sheetAt.getRow(0);
        //4.获取一个行
        Cell cell = row.getCell(1);
        System.out.println(cell.getStringCellValue());

        fileInputStream.close();

        System.out.println("文件读写成功");
    }

    @Test
    public  void  testWrite07() throws IOException {

        FileInputStream fileInputStream = new FileInputStream(PATH+"洲哥学习导入导出操作.xlsx");

        //1.获取一个工作薄 使用excel操作它都能设置
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        //2.获取一个工作表
        Sheet sheetAt = workbook.getSheetAt(0);
        //3.获取一个列
        Row row = sheetAt.getRow(0);
        //4.获取一个行
        Cell cell = row.getCell(1);
        System.out.println(cell.getStringCellValue());

        fileInputStream.close();

        System.out.println("文件读写成功");
    }

    /**
     * 获取整张表的数据
     * @throws IOException
     */
    @Test
    public void testCellType() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(PATH+"wms_warehouse_lv5_container.xls");
        //1.获取一个工作薄 使用excel操作它都能设置
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);

        //2.获取一个工作表
        Sheet sheetAt = workbook.getSheetAt(0);
        //3.获取一个列
        Row row = sheetAt.getRow(0);
        if (row!=null){
            int cellCount = row.getPhysicalNumberOfCells();
            for (int rowNum = 0; rowNum <cellCount ; rowNum++) {
                Cell cell = row.getCell(rowNum);
                System.out.print(cell.getStringCellValue()+"||");
            }
        }
        System.out.println();

        //获取表的内容
        int SheetCount = sheetAt.getPhysicalNumberOfRows();
        for (int rowNum = 0; rowNum <SheetCount ; rowNum++) {
            Row rowdata=sheetAt.getRow(rowNum);
            if (rowdata!=null){
                //读取列
                int cellCount = row.getPhysicalNumberOfCells();
                for (int cellNum = 0; cellNum <cellCount ; cellNum++) {
                    System.out.print("["+(rowNum+1)+"-"+(cellNum+1)+"]");

                    Cell  cell=rowdata.getCell(cellNum);
                    //匹配列的数据类型
                    if (cell!=null){
                        int celltype=cell.getCellType();
                        String cellvalue="";
                        switch (celltype){
                            case HSSFCell.CELL_TYPE_STRING://字符串
                                System.out.print("[String]");
                                cellvalue=cell.getStringCellValue();
                                break;
                            case  HSSFCell.CELL_TYPE_BOOLEAN://布尔
                                System.out.print("[BOOLEAN]");
                                cellvalue=String.valueOf(cell.getBooleanCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_BLANK://空
                                System.out.print("[BLANK]");
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC://数字,日期,普通数字
                                System.out.print("[NUMERIC]");
                                if (HSSFDateUtil.isCellDateFormatted(cell)){//日期
                                    System.out.print("[日期]");
                                    Date date = cell.getDateCellValue();
                                    cellvalue =new DateTime().toString("yyy-MM-dd");
                                }else{
                                    //不是日期格式
                                    System.out.print("[转换为字符串输出]");
                                    cell.setCellValue(HSSFCell.CELL_TYPE_STRING);

                                    cellvalue=cell.toString();
                                }
                                break;
                            case  HSSFCell.CELL_TYPE_ERROR:
                                System.out.println("[数据类型错误]");
                                break;
                        }
                        System.out.println(cellvalue);
                    }
                }
            }
        }
        fileInputStream.close();
        System.out.println();
    }

    @Test
    public void  testFormula() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(PATH+"公式.xls");

        //1.获取一个工作薄 使用excel操作它都能设置
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        //2.获取一个工作表
        Sheet sheetAt = workbook.getSheetAt(0);
        //3.获取一个列
        Row row = sheetAt.getRow(4);
        //4.获取一个行
        Cell cell = row.getCell(0);

        //拿到计算公式
        HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
        //输出单元格的内容
        int  celltype=cell.getCellType();
        switch (celltype){
            case Cell.CELL_TYPE_FORMULA://公式
                String formla =cell.getCellFormula();
                System.out.println(formla);

                //计算
                CellValue evaluate = formulaEvaluator.evaluate(cell);
                String cellvalue=evaluate.formatAsString();
                System.out.println(cellvalue);
                break;
        }
    }


    @Test
    public void     simpleRead() {
        String fileName =PATH+"easyTest.xls";
        // 写法2
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        //fileName保存路径 demoData实体类

        EasyExcel.read(fileName, DemoData.class,new DemoDataListener()).sheet().doRead();
    }
}

package yinzs;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.ListUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelWriteTest {

    String PATH="D:\\wenhao\\yinzs-pol\\";

    /**
     * 大文件写入HSSF最多只能生成65535行
     * 写入缓存 一次执行速度快
     * 后缀 xls
     * @throws IOException
     */
    @Test
    public  void  testWrite03() throws IOException {
        //1.创建一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.创建一张表
        Sheet sheet = workbook.createSheet("洲哥观众统计表");
        //3.创建一个行(1,1)
        Row row = sheet.createRow(0);
        //4。创建一个单元格
        Cell cell = row.createCell(0);
        cell.setCellValue("今日新增观众");
        //(1,2)
        Cell cell1 = row.createCell(1);
        cell1.setCellValue("666");
       //(2,1)
        Row row1=sheet.createRow(1);
        Cell cell2 = row1.createCell(0);
        cell2.setCellValue("当前时间");
        //(2,2)
        Cell rell3=row1.createCell(1);
        String dateTime = new DateTime().toString("yyy-MM-dd HH:mm:ss");
        rell3.setCellValue(dateTime);


        FileOutputStream fileOutputStream = new FileOutputStream(PATH+"洲哥学习导入导出操作.xls");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        System.out.println("文件写入成功");
    }

    /**
     * XSSF写入
     * 写入速度慢 但是存储量较大 比如存储20万条是没有问题的
     * 后缀 xlsx
     * @throws IOException
     */
    @Test
    public  void  testWrite07() throws IOException {
        //1.创建一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();

        //2.创建一张表
        Sheet sheet = workbook.createSheet("洲哥观众统计表");
        //3.创建一个行(1,1)
        Row row = sheet.createRow(0);
        //4。创建一个单元格
        Cell cell = row.createCell(0);
        cell.setCellValue("今日新增观众");
        //(1,2)
        Cell cell1 = row.createCell(1);
        cell1.setCellValue("666");
        //(2,1)
        Row row1=sheet.createRow(1);
        Cell cell2 = row1.createCell(0);
        cell2.setCellValue("当前时间");
        //(2,2)
        Cell rell3=row1.createCell(1);
        String dateTime = new DateTime().toString("yyy-MM-dd HH:mm:ss");
        rell3.setCellValue(dateTime);


        FileOutputStream fileOutputStream = new FileOutputStream(PATH+"洲哥学习导入导出操作.xlsx");

        workbook.write(fileOutputStream);

        fileOutputStream.close();
        System.out.println("文件写入成功");
    }

    /**
     * 写入大量数据 HSSF
     * @throws IOException
     */
    @Test
  public void Write03BeginData() throws IOException {
        //开始时间
        Long bengin=System.currentTimeMillis();
      HSSFWorkbook workbook = new HSSFWorkbook();

      Sheet sheet = workbook.createSheet();

      for (int rowNum = 0; rowNum < 65536; rowNum++) {
          Row row = sheet.createRow(rowNum);
          for (int cellNum = 0; cellNum <10 ; cellNum++) {
              Cell cell = row.createCell(cellNum);
              cell.setCellValue(cellNum);
          }
      }
      System.out.println("over");
      //结束时间
        Long end =System.currentTimeMillis();

      FileOutputStream fileOutputStream = new FileOutputStream(PATH + "test03WriteBegin.xls");
      workbook.write(fileOutputStream);
      fileOutputStream.close();

      System.out.println((double) (end-bengin)/1000);
  }

    /**
     * 写入大量数据 XSSF
     * @throws IOException
     */
    @Test
    public void Write07BeginData() throws IOException {
        //开始时间
        Long bengin=System.currentTimeMillis();
        XSSFWorkbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet();

        for (int rowNum = 0; rowNum < 100000; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for (int cellNum = 0; cellNum <10 ; cellNum++) {
                Cell cell = row.createCell(cellNum);
                cell.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        //结束时间
        Long end =System.currentTimeMillis();

        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "test07WriteBegin.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();

        System.out.println((double) (end-bengin)/1000);
    }

    /**
     *  XSS+redis
     * 写入大量数据 SXSSF
     * @throws IOException
     */
    @Test
    public void Write07BeginData2() throws IOException {
        //开始时间
        Long bengin=System.currentTimeMillis();
        SXSSFWorkbook workbook = new SXSSFWorkbook();

        Sheet sheet = workbook.createSheet();

        for (int rowNum = 0; rowNum < 100000; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for (int cellNum = 0; cellNum <10 ; cellNum++) {
                Cell cell = row.createCell(cellNum);
                cell.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        //结束时间
        Long end =System.currentTimeMillis();

        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "test07WriteBegin.xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();

        System.out.println((double) (end-bengin)/1000);
    }


    /**
     * 根据list写入
     */
    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;
    }

    /**
     * 最简单的写
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link DemoData}
     * <p>
     * 2. 直接写即可
     */
    @Test
    public void simpleWrite() {
        String fileName =PATH+"easyTest.xls";
        // 写法2
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        //fileName保存路径 demoData实体类
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

    }
}

重点踩坑!!!重点踩坑!!!重点踩坑!!!

使用easyexcel写入的时候 一直卡着不报错不输出 一直找不到原因 刚开始发现一直不进入监听器 结果是因为hasTest

    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

这个默认是false 记得改成true 就能看到自己的读取的信息啦

猜你喜欢

转载自blog.csdn.net/yzs2022/article/details/127375108