话不多说,直接贴代码,懂的自然懂
package com.iflytek.qb.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ImportExcel<T> {
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
Class<T> clazz;
public ImportExcel (Class<T> clazz) {
this.clazz = clazz;
}
public Collection<T> importExcel(InputStream in,int titleRowIndex, String...pattern) {
Collection<T> dist = new ArrayList<T>();
try {
/**
* 类反射得到调用方法
*/
// 得到目标目标类的所有的字段列表
Field[] fields = clazz.getDeclaredFields();
// 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
Map<String, Method> fieldMap = new HashMap<String, Method>();
// 循环读取所有字段
for (Field field : fields) {
// 得到单个字段上的Annotation
ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class);
// 如果标识了Annotationd
if (excelAnnotation != null) {
String fieldName = field.getName();
// 构造设置了Annotation的字段的Setter方法
String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// 构造调用的method
Method setMethod = clazz.getMethod(setMethodName, new Class[] {field.getType()});
// 将这个method以Annotaion的名字为key来存入
fieldMap.put(excelAnnotation.exportName().trim(), setMethod);
}
}
/**
* excel的解析开始
*/
// 得到工作表
Workbook book = WorkbookFactory.create(in);
// 得到第一页
Sheet sheet = book.getSheetAt(0);
// 得到第一面的所有行
Iterator<Row> row = sheet.rowIterator();
/**
* 标题解析
*/
Row titleRow=null;
// 得到第一行,也就是标题行
for(int i=0;i<titleRowIndex;i++) {
titleRow = row.next();
}
// 得到第一行的所有列
Iterator<Cell> cellTitle = titleRow.cellIterator();
// 将标题的文字内容放入到一个map中
Map<Integer, String> titleMap = new HashMap<Integer, String>();
// 从标题第一列开始
int i = 0;
// 循环标题所有的列
while (cellTitle.hasNext()) {
Cell cell = (Cell) cellTitle.next();
String value = cell.getStringCellValue().trim();
titleMap.put(i, value);
i++;
}
/**
* 解析内容行
*/
while (row.hasNext()) {
// 标题下的第一行
Row rown = row.next();
// 行的所有列
Iterator<Cell> cellBody = rown.cellIterator();
// 得到传入类的实例
T tObject = clazz.newInstance();
// 遍历一行的列
int col = 0;
while (cellBody.hasNext()) {
Cell cell = (Cell) cellBody.next();
// 这里得到此列的对应的标题
String titleString = titleMap.get(col++);
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
if (fieldMap.containsKey(titleString)) {
Method setMethod = fieldMap.get(titleString);
//得到setter方法的参数
Type[] types = setMethod.getGenericParameterTypes();
//只要一个参数
String xclass = String.valueOf(types[0]);
//判断参数类型
if ("class java.lang.String".equals(xclass)) {
setMethod.invoke(tObject, getCellValue(cell));
} else if ("class java.util.Date".equals(xclass)) {
setMethod.invoke(tObject, cell.getDateCellValue());
} else if ("class java.lang.Boolean".equals(xclass)) {
Boolean boolName = true;
if ("否".equals(cell.getStringCellValue())) {
boolName = false;
}
setMethod.invoke(tObject, boolName);
} else if ("class java.lang.Integer".equals(xclass)) {
setMethod.invoke(tObject, new Integer(String.valueOf((int)cell.getNumericCellValue())));
} else if ("class java.lang.Long".equals(xclass)) {
setMethod.invoke(tObject, new Long(cell.getStringCellValue()));
} else {
//
}
}
}
dist.add(tObject);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
return dist;
}
// excel判断单元格类型及转换
private String getCellValue(Cell cell) {
String cellValue = "";
DecimalFormat df = new DecimalFormat("#");
if(cell!=null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getRichStringCellValue().getString().trim();
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
cellValue = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
cellValue = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
cellValue = format.format(value);
}
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
}
return cellValue;
}
}
}
注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAnnotation {
// excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入
public String exportName();
}
在类属性上加注解