敏捷开发-基于JAVA POI 使用基础Excel解析

Excel

前提

  • 了解POI解析
    (可粗略查找下了解如何基本解析) : 本文仅针对部分类型的Excel格式解析, 代码进行优化。

1. 一行一行形式的Excel

数据:

姓名手机号年龄出生日期性别备注
张老师15375111111181999/1/1备注1
张老师15375111111181999/1/1备注1
张老师15375111111181999/1/1备注1

分析:

1.
问题: 如何对每行cell 简洁的获取到自己想要的数据。
方案: 实现CellReader 基于POI的Row 的 数据读取器

public class POIExcelCellReader {

    public POIExcelCellReader(Row row) 

    public Cell next() throws IOException 

    public String nextString() throws IOException 

    public Integer nextInt() throws IOException 

    public Date nextDate() throws IOException 

}

2.
问题: 统一解析接口
方案: 使用模板模式 对数据预先设置好解析策略 抽象每行的具体解析

public abstract class POIExcelRowParser <R> extends POIExcelParser {
    public List<R> parse() throws ExcelParseException
    //每个模板各自实现解析
    protected abstract boolean parseRow(List<R> entrys, int index, POIExcelCellReader cellReader) throws ExcelParseException, IOException ;

    protected boolean parseHeader(Iterator<Row> iterator)

    protected void end()

}

下载代码示例:

Demo下载地址: 。。。

简介的使用:

//1.Model
class User {
    private String name;
    private String gender;
    private String age;
    private Date birth;
    private String phone;
    private String remark;
}
//2.解析器
public class UserExcelParser extends POIExcelRowParser<User>{
    @Override
    protected boolean parseRow(List<User> entrys, int index,
            POIExcelCellReader cellReader) throws ExcelParseException,
            IOException {

        //数据读取
        String name = cellReader.nextString();
        String phone = cellReader.nextString();
        Integer age = cellReader.nextInt();
        Date date = cellReader.nextDate();
        String gender = cellReader.nextString();
        String remark = cellReader.nextString();

        //数据检查
//      if (!PhoneUtils.isPhone(phone)) {
//          throw new ExcelParseException(index, "号码格式错误");
//      }
//      联合数据库检查
//

        //数据整合 添加到entrys
        User entry = new User();
        entry.setPhone(phone);
        entrys.add(entry);
        return true;
    }
}
try {
    is = new FileInputStream(excel);

    userExcelParser.load03Workbook(is);
    users= userExcelParser.parse();

    打印("导入完成,数量:" + users.size());
} catch (ExcelParseException e) {
    打印("导入错误 : " + e.getMessage());
} finally {
    if ( is!= null) {
        is.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值