自定义注解:

package com.example.demo.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Created by linjiaming*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation {String headName();int order();String datePattern() default "yyyyMMdd HH:mm:ss";enum DataType {String,Number,Date,}/*** 数据类型,可以是String,Number(数字型),Date等类型* @return*/DataType type() default DataType.String;}

实体类:

package com.example.demo.entity;import com.example.demo.annotation.ExcelAnnotation;
import com.example.demo.annotation.ExcelAnnotation.DataType;
import java.util.Date;
import lombok.Data;@Data
public class Student {private Long id;@ExcelAnnotation(headName = "学号", order =0)private String stuNo;@ExcelAnnotation(headName = "姓名", order =1)private String name;@ExcelAnnotation(headName = "学院", order =3)private String academy;@ExcelAnnotation(headName = "专业",order = 4)private String major;@ExcelAnnotation(headName = "年级", order = 5)private String grade;@ExcelAnnotation(headName = "班级", order = 6)private String classes;@ExcelAnnotation(headName = "年龄", order = 2)private String age;@ExcelAnnotation(headName = "入学日期", order = 7, datePattern ="yyyy/MM/dd HH:mm:ss",type = DataType.Date)private Date entryDate;}

excel导入导出工具类:

/*** Created by linjiaming*/
public class ExcelUtils {private static ExcelUtils instance;private ExcelUtils(){}/*** 单例模式* @return*/public static ExcelUtils getInstance() {if (instance == null) {instance = new ExcelUtils();}return instance;}/*** excel的导出* @param out* @param infos*/public void exportExcel (OutputStream out, List<?> infos) {try {XSSFWorkbook xssfWorkbook = new XSSFWorkbook();XSSFSheet sheet = xssfWorkbook.createSheet();sheet.createRow(0);Map<Field,Integer> map = new LinkedHashMap<>();for (Object o : infos ) {Field[] fields = o.getClass().getDeclaredFields();for (Field field : fields) {if (field.isAnnotationPresent(ExcelAnnotation.class)) {ExcelAnnotation annotation = field.getAnnotation(ExcelAnnotation.class);map.put(field, annotation.order());}}}List<Entry<Field,Integer>> list = new ArrayList<Entry<Field,Integer>>(map.entrySet());Collections.sort(list, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));List<Field> excelFields = new ArrayList<>();for(Entry<Field,Integer> map1 : list){excelFields.add(map1.getKey());}List<ExcelAnnotation> annotations = new ArrayList<>();for (Field excelField : excelFields) {annotations.add(excelField.getAnnotation(ExcelAnnotation.class));}addDataToExcel(xssfWorkbook, infos, excelFields, annotations, sheet);xssfWorkbook.write(out);} catch (Exception e) {e.printStackTrace();}}private <T> void addDataToExcel(XSSFWorkbook wb, List<T> dataset,List<Field> excelFields, List<ExcelAnnotation> attributes,Sheet sheet)throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, ParseException {XSSFCellStyle style = wb.createCellStyle();// 居中style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);// excel放入第一行列的名称Row row = sheet.createRow(0);for (int j = 0; j < excelFields.size(); j++) {Cell cell = row.createCell(j);ExcelAnnotation oneAttribute = attributes.get(j);cell.setCellValue(oneAttribute.headName());cell.setCellStyle(style);}// 添加数据到excelfor(int i=0;i<dataset.size();i++) {// 数据行号从1开始,因为第0行放的是列的名称row = sheet.createRow(i+1);for(int j=0;j<attributes.size();j++) {Cell cell = row.createCell(j);ExcelAnnotation annotation = attributes.get(j);style = wb.createCellStyle();// 居中style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);// 四个边框style.setBorderBottom(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);style.setBorderTop(BorderStyle.THIN);cell.setCellStyle(style);// 根据属性名获取属性值String cellValue = BeanUtils.getProperty( dataset.get(i), excelFields.get(j).getName());if (DataType.Date.equals(annotation.type())){String date = DateTimeUtil.getFormatDateFromGLWZString(cellValue, annotation.datePattern());cell.setCellValue(date);}else {cell.setCellValue(cellValue);}}}}/*** excel的导入* @param inputStream* @param clazz* @return* @throws IOException* @throws InstantiationException* @throws IllegalAccessException* @throws InvocationTargetException* @throws NoSuchMethodException*/public  List<?> importExcel(InputStream inputStream, Class<?> clazz)throws IOException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {Workbook workbook = WorkbookFactory.create(inputStream);Sheet sheet = workbook.getSheetAt(0);Row titleCell = sheet.getRow(0);List<Object> dataList = new ArrayList<>(sheet.getLastRowNum());Object datum;Map<String, Field> fieldMap = getFieldMap(clazz);for (int i = 1; i <= sheet.getLastRowNum(); i++) {Row row = sheet.getRow(i);datum = clazz.newInstance();int minCell = row.getFirstCellNum();int maxCell = row.getLastCellNum();for (int cellNum = minCell; cellNum <= maxCell; cellNum++) {Cell title = titleCell.getCell(cellNum);if (title == null) {continue;}String tag = title.getStringCellValue();Field field = fieldMap.get(tag);if (field == null) {continue;}Class<?> type = field.getType();Object value = null;Cell cell = row.getCell(cellNum);if (cell == null) {continue;}if (type.equals(Date.class)){value = cell.getDateCellValue();} else {value = cell.getStringCellValue();}PropertyUtils.setProperty(datum, field.getName(), value);}dataList.add(datum);}return dataList;}/*** key :headName  val:该名称对应的字段* @param clazz* @param <T>* @return*/private static <T> Map<String, Field> getFieldMap(Class<T> clazz) {Field[] fields = clazz.getDeclaredFields();Map<String, Field> fieldMap = new HashMap<>();for (Field field : fields) {if (field.isAnnotationPresent(ExcelAnnotation.class)) {ExcelAnnotation annotation = field.getAnnotation(ExcelAnnotation.class);fieldMap.put(annotation.headName(), field);}}return fieldMap;}
@Slf4j
public class DateTimeUtil {private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/*** 获得所需要的日期格式** @param date* @param format yyyy-MM-dd HH:mm:ss* @return*/public static Date getFormatDateFromString(String date, String format) {SimpleDateFormat formatter = new SimpleDateFormat(format);Date formatDate = null;try {formatDate = formatter.parse(date);} catch (ParseException e) {e.printStackTrace();}return formatDate;}public static String getFormatDateFromGLWZString(String strdate, String format)throws ParseException {DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);Date date =df.parse(strdate);//     System.out.println(date.toString());SimpleDateFormat sdf=new SimpleDateFormat(format);return sdf.format(date);}
}

简单测试:

public static void main(String[] args)throws IOException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {ExcelUtils excelUtils = getInstance();String filepath = "D:\\学生信息表.xlsx";File file = new File(filepath);List<?> objects =  excelUtils.importExcel(new FileInputStream(file), Student.class);System.out.println(objects);}

通过自定义注解+反射的形式,使用POI实现excel的导入导出相关推荐

  1. 蓄力-利用POI进行excel的导入导出(包含图片)

    这里写自定义目录标题 利用POI进行excel的导入导出 引入的jar包 excel导入 主方法: 将excel里面的图片转成数据 xls格式 xlsx格式 将图片数据转成字节流的方式传输到FTP服务 ...

  2. 手摸手教学-利用原生POI对excel的导入导出以及阿里的easyexcel的基本操作

    文章目录 原生POI对excel的导入导出以及阿里的easyexcel的基本操作 首先是最原始的POI操作excel 其次是POI操作excel对数据库的导入导出 最后是阿里的easyexcel的简单 ...

  3. Poi的Excel的导入导出 支持2007

    需要导入 poi-3.7.jar commons-io-2.4.jar Excel2003导出 import java.io.File; import java.io.FileOutputStream ...

  4. 通过POI操作Excel的导入导出

    项目地址https://github.com/zhuhaitao666/excel.git 这里罗列部分核心代码 1.引入依赖和配置 <dependency><groupId> ...

  5. java自定义注解实现excel数据导入导出,设置单元格数据验证与生成省市区多列联动效果

    本文通过自定义注解实现excel数据导入导出.以及设置excel文件中列数据验证,即用户在excel文件中输入数据时就可以对数据格式验证是否符合,节省了程序中过多的数据验证操作,注解还额外提供了一系列 ...

  6. POI之excel固定模板导出

    POI之excel固定模板导出 一.简介 二.excel模板 三.项目中maven依赖 四.Excel模板操作代码 五.Controller层excel模板导出接口代码 六.导出excel 一.简介 ...

  7. POI读取Excel模板并导出大量数据

    POI读取Excel模板并导出大量数据 我在使用XSSFWorkbook读取Excel模板并导出大量数据(百万级)时,发现很长时间没有响应,debugger模式发现在读取第三四十万条数据时,程序直接停 ...

  8. 【开发随机】JAVA+POI+自定义注解+反射构建自定义工具类实现快捷简便的Excel模板化导出(附demo代码)

    220907更新 项目UAT期间,用户反映了一个问题,数据量稍大的情况下,会出现"从某一行开始,往下所有行设置的字体和字体大小不生效"的BUG. 经过排查,发现原因是:POI的XS ...

  9. 玩转POI、EasyExcel报表导入导出!

    POI.EasyExcel报表导出 前言 一.POI操作Excel 1.1 导入依赖包 1.2 编写测试代码: 1.3 03和07版本的区别 二.大文件写入 2.1 大文件写HSSF 2.2 大文件写 ...

  10. java使用POI实现Excel批量导入数据。

    1.背景 项目中有使用easypoi,处理常规excel问题,但是现在有个需求,需要动态生成导出的报表字段.同时,根据导入的excel,增加数据信息.(有可能会出现,导入的报表是几天前下载的,不会最新 ...

最新文章

  1. MySQL 的 find_in_set函数使用方法
  2. Linux cp命令如何拷贝整个目录下所有文件
  3. 有温度传感器的风机控制系统C语言,毕业论文--基于单片机的工业风机控制器设计与实现.doc...
  4. 作者:李文静,山东农业信息中心助理农经师。
  5. 2018年软考网络规划设计师考试通过经验分享
  6. java使用httpclient封装post请求和get的请求
  7. 【Head First 设计模式】-简单工厂模式读后总结
  8. 10.7 csp-s模拟测试63 Median+Game+Park
  9. 使用Json封装scroll,已处理其兼容性问题
  10. file does not exist 阿里云OSS图片上传遇到的问题
  11. 吴恩达深度学习笔记2.1 二分分类
  12. Visual Studio 201~ Code 格式检查
  13. java画菱形_JavaSE之绘制菱形
  14. 揭露卖劣质U盘黑心商家的利器
  15. 双向链表的插入及删除图解
  16. SVN中删除彻底删除某一个版本
  17. 直角坐标系和极坐标系
  18. 贪心算法--最小耗费生成树(Prim算法)
  19. 动态规划求解多段图问题
  20. with check option的使用

热门文章

  1. 代码大全(第2版)_2021【公式大全3.0版】【(数一)第371页】【(数二)第283页】【(数三)第324页】【有关矩阵秩的重要结论】6)~...
  2. 再谈Spring(二):AOP面向切面编程 - Aspect 拦截器
  3. Android5.1-s5p6818平台adb push 、adb install/uninstall的疑问
  4. Unity Burst 用户指南
  5. 服务器系统事件id1001,win10系统玩游戏出现蓝屏事件ID1001的解决方法
  6. Windows下强制删除文件或文件夹
  7. TensorFlow - 正弦曲线
  8. 9个动作让网站3天被百度收录!
  9. AI新技术:利用神经网络对图片进行超级压缩
  10. VB.net单exe文件内MP3和WAV音乐文件播放