java操作Excel两种方式EasyExcel 和POI

一、POI

1.引入依赖

复制代码
<!-- 03 xls-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

<!-- 07 xlsx -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

<!-- 日期格式化 -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.4</version>
</dependency>

2.读取Excel

复制代码
package com.example;

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.*;

public class Test {
    public static void main(String[] args) throws Exception {
        //获取文件的数据流
        InputStream inputStream = new FileInputStream("D:\\java\\测试.xls");
        //创建文件对象
        Workbook workbook = new HSSFWorkbook(inputStream);
        //获取Sheet
        Sheet sheet = workbook.getSheetAt(0);
        //获取行
        Row row = sheet.getRow(0);
        //获取列
        Cell cell = row.getCell(0);
        String stringCellValue = cell.getStringCellValue();
        System.out.println(stringCellValue);
        inputStream.close();
    }
}

3.写入Excel

复制代码
package com.example;

import org.apache.poi.hssf.usermodel.HSSFCell;
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 java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        //获取文件的数据流
        InputStream inputStream = new FileInputStream("D:\\java\\demo.xls");
        //创建文件对象
        Workbook workbook = new HSSFWorkbook(inputStream);
        //获取Sheet
        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i < rows; i++) {
            Row row = sheet.getRow(i);
            int cells = row.getPhysicalNumberOfCells();
            for (int j = 0; j < cells; j++) {
                Cell cell = row.getCell(j);
                int type = cell.getCellType();
                String value = "";
                switch (type){
                    case HSSFCell.CELL_TYPE_STRING:
                        value = cell.getStringCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        value = cell.getStringCellValue();
                        break;
                }
                System.out.print(value+" ");
            }
            System.out.println();
        }
        inputStream.close();
    }
}

二、EasyExcel

EasyExcel 会将 Excel 数据和 Java 对象之间绑定起来

1.引入依赖

复制代码
<!-- EasyExcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>

2.创建跟 Excel 数据格式对应的 Java 类

复制代码
package com.example;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

import java.util.Date;

@Data
public class ExcelVO {
    @ExcelProperty("ID")
    private Integer id;
    @ExcelProperty("公司名称")
    private String name;
    @ExcelProperty("停车场")
    private String park;
    @ExcelProperty("车牌号")
    private String number;
    @ExcelProperty("支付类别")
    private String type;
    @ExcelProperty("支付金额(元)")
    private Integer money;
    @ExcelProperty("支付时间")
    private Date time;
}

3.读取数据

复制代码
package com.example;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        InputStream inputStream = new FileInputStream("D:\\java\\demo.xls");
        EasyExcel.read(inputStream)
                .head(ExcelVO.class)
                .sheet()
                .registerReadListener(new AnalysisEventListener<ExcelVO>() {
                    @Override
                    public void invoke(ExcelVO o, AnalysisContext analysisContext) {
                        System.out.println(o);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        System.out.println("文件解析完成");
                    }
                }).doRead();
    }
}

4.写数据

复制代码
package com.southwind.handler;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {

    private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>();
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }

            }
        }
    }

    private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch (type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}

package com.example;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.southwind.handler.CustomCellWriteHandler;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Test {
    public static void main(String[] args) throws Exception {
        List<ExcelVO> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ExcelVO excelVO = new ExcelVO();
            excelVO.setId(i+1);
            excelVO.setType("临时车");
            excelVO.setTime(new Date());
            excelVO.setPark("软件园停车场");
            excelVO.setMoney(100);
            excelVO.setNumber("电A123456");
            excelVO.setName("Java科技有限公司");
            list.add(excelVO);
        }
        OutputStream outputStream = new FileOutputStream("D:\\java\\demo2.xls");
        EasyExcel.write(outputStream,ExcelVO.class)
                .registerWriteHandler(new CustomCellWriteHandler())
                .sheet("停车缴费记录")
                .doWrite(list);

    }
}
相关推荐
沈浩(种子思维作者)17 小时前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
Cherry的跨界思维17 小时前
28、AI测试环境搭建与全栈工具实战:从本地到云平台的完整指南
java·人工智能·vue3·ai测试·ai全栈·测试全栈·ai测试全栈
それども17 小时前
Apache POI XSSFWorkbook 和 SXSSFWorkbook 的区别
apache·excel
njsgcs18 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
alonewolf_9918 小时前
JDK17新特性全面解析:从语法革新到模块化革命
java·开发语言·jvm·jdk
io_T_T18 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
一嘴一个橘子18 小时前
spring-aop 的 基础使用(啥是增强类、切点、切面)- 2
java
sheji341618 小时前
【开题答辩全过程】以 中医药文化科普系统为例,包含答辩的问题和答案
java
华研前沿标杆游学18 小时前
2026年走进洛阳格力工厂参观游学
python
Carl_奕然18 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析