java操作excel

使用Java操作excel可以使用两种方式:
关于表格导入导出,市面上比较知名的开源就是 Apache 的POI 和 阿里巴巴的 EasyExcel了。EasyExcel 也是对 POI 的改进和封装, 更加好用。
1:POI是Apache 的开源项目,由Java编写的跨平台 Java API,可操作Microsoft Office。
	借助POI,可以方便的生成数据报表,数据批量上传,数据备份等工作。但是将文件数据一
	次性全部加载到内存可能导致OOM。
2:EasyExcel 能大大减少内存占用的主要原因是在解析 Excel 时没有将文件数据一次性全部
	加载到内存中,而是从磁盘上一行行读取数据,逐个解析。

java操作excel_第1张图片
加入依赖:

 <!--  xls 03版本的
        &lt;!&ndash; https://mvnrepository.com/artifact/org.apache.poi/poi &ndash;&gt;
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        &lt;!&ndash; xls 07版本的 &ndash;&gt;
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>-->
        <!--日期格式化的工具-->
        <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>

poi简单操作excel

package com.dongmu;

import com.sun.corba.se.spi.orbutil.threadpool.Work;
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;
import org.joda.time.DateTime;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TestExcelWrite {
    public static void main(String[] args) throws Exception {
//        Workbook workbook = new HSSFWorkbook();//xls
//        Workbook workbook = new XSSFWorkbook();//xlsx

//        write(workbook,"D:\\word文档\\电子版练习册\\JAVA\\15:easyExcelAndPOI\\Excel\\07版本.xlsx");

        read();

    }

    public static void write(Workbook workbook,String path) throws Exception {
        /*创建一共表*/
        Sheet sheet = workbook.createSheet("冬木学习技术栈掌握表");
        /*创建一行*/
        Row row1 = sheet.createRow(0);
        /*创建一个单元格*/
        Cell cell = row1.createCell(0);
        /*设置单元格的内容*/
        cell.setCellValue("学习的内容");
        cell = row1.createCell(1);

        cell.setCellValue("java操作ecxel");

        Row row2 = sheet.createRow(1);

        cell = row2.createCell(0);

        cell.setCellValue("学习的时间");

        cell = row2.createCell(1);

        cell.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

        FileOutputStream fileOutputStream = new FileOutputStream(path);

        workbook.write(fileOutputStream);

        fileOutputStream.flush();
        fileOutputStream.close();
    }

    public static void read() throws Exception{
//        FileInputStream stream = new FileInputStream("D:\\word文档\\电子版练习册\\JAVA\\15:easyExcelAndPOI\\Excel\\07版本.xlsx");
        FileInputStream stream = new FileInputStream("D:\\word文档\\电子版练习册\\JAVA\\15:easyExcelAndPOI\\Excel\\03版本.xls");

//        Workbook workbook = new XSSFWorkbook(stream);
        Workbook workbook = new HSSFWorkbook(stream);

        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(0);

        Cell cell = row.getCell(0);
        String stringCellValue = cell.getStringCellValue();

        System.out.println(stringCellValue);
    }
}


批量地读取excel表中的数据:

package com.dongmu;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.helpers.XSSFFormulaUtils;

import java.io.FileInputStream;

public class TestExcelRead {
    public static void main(String[] args) throws Exception {


        FileInputStream inputStream = new FileInputStream("D:\\word文档\\武汉理工大学\\过去文件夹\\通信1904班云动会参赛情况.xlsx");

        Workbook workbook = new XSSFWorkbook(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(2);

        int physicalNumberOfCells = row.getPhysicalNumberOfCells();

        for (int i = 0; i < physicalNumberOfCells; i++) {
            Cell cell = row.getCell(i);
            String stringCellValue = cell.getStringCellValue();

            System.out.print(stringCellValue+"| ");
        }
        System.out.println("一共"+physicalNumberOfCells+"列。");

        int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();

        for (int i = 4; i < physicalNumberOfRows; i++) {
            Row row1 = sheet.getRow(i);

            int physicalNumberOfCells1 = row1.getPhysicalNumberOfCells();

            for (int i1 = 0; i1 < physicalNumberOfCells1; i1++) {
                Cell cell = row1.getCell(i1);
                if (cell!=null){
                    int cellType = cell.getCellType();
                    switch (cellType){
//                    case XSSFCell.
                        case XSSFCell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue()+"| ");
                            break;
                        case XSSFCell.CELL_TYPE_BLANK:
                            System.out.print("空值| ");break;
                        case XSSFCell.CELL_TYPE_BOOLEAN:
                            System.out.print(cell.getBooleanCellValue()+"| ");
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
                            //获得计算公式
                            String cellFormula = cell.getCellFormula();
                            CellValue evaluate = formulaEvaluator.evaluate(cell);
                            String s = evaluate.formatAsString();
                            System.out.print(s+"| ");
                            break;
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)){
                                System.out.print(cell.getDateCellValue()+"| ");
                            }else {
                                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                                System.out.print(cell.getStringCellValue()+"| ");
                            }
                            break;
                        case XSSFCell.CELL_TYPE_ERROR:
                            System.out.print("数据类型错误| ");
                            break;
                    }
                }
//                System.out.println();
            }
            System.out.println();
        }

    }
}


使用EasyExcel操作excel
加入依赖


    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

1:写数据

创建一个实体类对应excel表中的字段数据
package com.dongmu.easyExcel;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
@EqualsAndHashCode
public class DemoData {
    @ExcelProperty("字符串标题")
    private String string;
    @ExcelProperty("日期标题")
    private Date date;
    @ExcelProperty("数字标题")
    private Double doubleData;
//     * 忽略这个字段


    @ExcelIgnore
    private String ignore;
}

将这个实体类保存的数据封装在一个list集合中
private static List<DemoData> data() {
        List<DemoData> list = ListUtils.newArrayList();
        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;
    }
编写程序写出数据到excel
@Test
    public void simpleWrite() {
        // 注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照 重复多次写入
        // 写法1 JDK8+
        // since: 3.0.0-beta1
        String fileName = "D:\\word文档\\电子版练习册\\JAVA\\15:easyExcelAndPOI\\Excel\\easyTest.xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return TestEasyExcel.data();
                });
	}

2:读数据

直接进行读取
@Test
    public void simpleRead() {
        // 写法1:JDK8+ ,不用额外写一个DemoDataListener
        // since: 3.0.0-beta1
        String fileName = "D:\\word文档\\电子版练习册\\JAVA\\15:easyExcelAndPOI\\Excel\\easyTest.xlsx";
        // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(fileName, DemoData.class, new PageReadListener<DemoData>(dataList -> {
            for (DemoData demoData : dataList) {
//                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
                System.out.println("读取到一条数据{}"+ JSON.toJSONString(demoData));
            }
        })).sheet().doRead();
    }

如果涉及到将读取到的数据存储到数据库,和更多的样式设置,参照
https://www.yuque.com/easyexcel/doc/read讲解非常详细。

你可能感兴趣的:(poi,easyExcel,java,apache,开发语言)