Excel
前提
- 了解POI解析
(可粗略查找下了解如何基本解析) : 本文仅针对部分类型的Excel格式解析, 代码进行优化。
1. 一行一行形式的Excel
数据:
姓名 | 手机号 | 年龄 | 出生日期 | 性别 | 备注 |
---|---|---|---|---|---|
张老师 | 15375111111 | 18 | 1999/1/1 | 男 | 备注1 |
张老师 | 15375111111 | 18 | 1999/1/1 | 男 | 备注1 |
张老师 | 15375111111 | 18 | 1999/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();
}
}