使用Apache POI包导入Excel时是需要根据行和列取到对应的值,因此取值时需要知道该列所对应的值应存放到对象的那个字段中去,表格出现变动就会变的比较麻烦,因此此处使用自定义注解的方式,在对象中标明该属性所对应的表头,从程序中遍历表头找到与之对应的单元格,方便数据的导入。
所需的jar包:(用了一下工具类,因此多导入了两个包)
org.apache.poi poi 3.17 org.apache.poi poi-ooxml 3.17 commons-beanutils commons-beanutils 1.9.2 org.apache.commons commons-lang3 3.2.1
自定义注解:
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.FIELD ,ElementType.TYPE})public @interface ExcelIn { /** * 导入sheet名称 * @return */ String sheetName() default ""; /** * 字段对应的表头名称 * @return */ String title() default "";}
接收导入数据的实体:
@ExcelIn(sheetName = "用户信息")public class UserInfo { private String id; @ExcelIn(title = "姓名") private String name; @ExcelIn(title = "年龄") private Integer age; @ExcelIn(title = "出生日期") private Date birthday;}
导入Excel数据:
public class ExcelReader{ private static BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); static { beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.DateConverter(null), java.util.Date.class); } /** * 表头名字和对应所在第几列的下标,用于根据title取到对应的值 */ private final Map title_to_index = new HashMap<>(); /** * 所有带有ExcelIn注解的字段 */ private final List fields = new ArrayList<>(); /** * 统计表格的行和列数量用来遍历表格 */ private int firstCellNum = 0; private int lastCellNum = 0; private int firstRowNum = 0; private int lastRowNum = 0; private String sheetName ; private HSSFSheet sheet ; public List read(InputStream in , Class clazz) throws Exception { gatherAnnotationFields(clazz); configSheet(in); configHeader(); List rList= null; try { rList = readContent(clazz); } catch (IllegalAccessException e) { throw new Exception(e); } catch (InstantiationException e) { throw new Exception(e); } catch (InvocationTargetException e) { throw new Exception(e); } return rList ; } private List readContent(Class clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null ; HSSFRow row = null ; List
测试导入结果:
@RunWith(SpringRunner.class)@SpringBootTestpublic class Test { @org.junit.Test public void t(){ try{ File file = new File("d:/abc.xls"); ExcelReaderreader = new ExcelReader<>(); InputStream is = new FileInputStream(file); List list = reader.read(is,UserInfo.class); if (CollectionUtils.isNotEmpty(list)) { for (UserInfo u : list) { System.out.println("姓名:" + u.getName() + " ,年龄:" + u.getAge() + " ,出身日期:" + u.getBirthday()); } } }catch (Exception e){ e.printStackTrace(); } }}
导入的Excel数据:(Excel的sheet名称为接收实体对象的sheetName)
结果展示: