java excel上传--poi
工作中很多批量上传需求不同,每个需求都要写一次批量上传代码,太烦。。决定写一个通用工具,此代码复制即用。需要改进的地方请评论区留言
方法调用传参例子:
上传文件中列的字段对应的是对象的属性
String[] fieldsName = new String[]{"carModelName","salePrice"};
此参数是上传文件中列必传字段对应对象的属性
String[] fieldsIsNull = new String[]{"carModelName"};
注:数组属性顺序必须和文件中顺序一样,解析文件时赋值不会赋错字段
public static final String OFFICE_EXCEL_2003_POSTFIX = "xls"; public static final String OFFICE_EXCEL_2007_POSTFIX = "xlsx"; public static final String EMPTY = ""; public static final String POINT = ".";
/
**
* 通过反射处理以获得的数据 * @param */ public T reflectDeal(T className, Cell cell, String fieldName){ Class aClass = null; try { aClass = className.getClass(); Field[] declaredFields = aClass.getDeclaredFields(); for (Field field:declaredFields) { field.setAccessible(true); String names = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length()); if(field.getName().equals(fieldName) && field.getType().getName().equals("java.math.BigDecimal")){ aClass.getMethod("set"+names,BigDecimal.class).invoke(className,new BigDecimal(""+cell)); }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.String")){ aClass.getMethod("set"+names,String.class).invoke(className,cell.getStringCellValue().toString()); }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Integer")){ aClass.getMethod("set"+names,Integer.class).invoke(className,cell); }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Double")){ aClass.getMethod("set"+names,Double.class).invoke(className,cell); } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return className; } /** * 本段代码解析xls文件 * @param */ public List<T> analysisXls(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull) { int totalrows = 0; int totalCell = 0; List<T> list = new ArrayList(); logger.info("==================== 开始解析xls文件 ========================="); //流读取文件 //创建文件 HSSFWorkbook wb = null; try { wb = new HSSFWorkbook(in); //读取页数 for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){ Sheet xs = wb.getSheetAt(num); if(xs == null){ continue; } totalrows = xs.getLastRowNum()+1; for (int rnum = 1 ; rnum < totalrows ; rnum ++){ boolean flag = false; T o = null; try { o = (T)clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } Row row = xs.getRow(rnum); if(row != null){ totalCell = row.getLastCellNum(); int nullCellNumb = 0; for (int cnum = 0 ; cnum < totalCell ; cnum ++){ Cell cell = row.getCell(cnum); if(null == cell){ nullCellNumb++; if(nullCellNumb>=10){ break; } continue; } if( cell != null && !"".equals(cell.toString().trim())){ this.reflectDeal(o, cell, fieldsName[cnum]); }else { for (int x=0;x<fieldsIsNull.length;x++){ if(fieldsIsNull[x].equals(fieldsName[cnum])){ flag = true; break; } } } } if (flag){ continue; } list.add(o); }else { return list; } } } } catch (IOException e) { e.printStackTrace(); }finally { try { in.close(); if(null != wb){ wb.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; }
/**
* 本段代码解析xlsx文件 * @param * @param clazz * @param fieldsName * @return */ public List<T> analysisXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull){ int totalrows = 0; int totalCell = 0; List<T> list = new ArrayList(); logger.info("==================== 开始解析xlsx文件 ========================="); //流读取文件 //创建文件 XSSFWorkbook wb = null; try { wb = new XSSFWorkbook(OPCPackage.open(in)); //读取页数 for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){ Sheet xs = wb.getSheetAt(num); if(xs == null){ continue; } totalrows = xs.getLastRowNum()+1; for (int rnum = 1 ; rnum < totalrows ; rnum ++){ boolean flag = false; T o = (T)clazz.newInstance(); Row row = xs.getRow(rnum); if(row != null){ totalCell = row.getLastCellNum(); int nullCellNumb = 0; for (int cnum = 0 ; cnum < totalCell ; cnum ++){ Cell cell = row.getCell(cnum); if(null == cell){ nullCellNumb++; if(nullCellNumb>=10){ break; } continue; } if( cell != null && !"".equals(cell.toString().trim())){ nullCellNumb = 0; this.reflectDeal(o, cell, fieldsName[cnum]); }else { for (int x=0;x<fieldsIsNull.length;x++){ if(fieldsIsNull[x].equals(fieldsName[cnum])){ flag = true; break; } } } } if (flag){ continue; } list.add(o); }else { return list; } } } } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvalidFormatException e) { logger.info("======= XSSF创建文件失败 ===="); e.printStackTrace(); }finally { try { in.close(); if(null != wb){ wb.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; }
/**
*此段代码区分e'xcel版本,分别调用哪个方法 * @param * @param clazz * @param fieldsName * @return * @throws IOException */ public List<T> readxlsAndXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String fileName,String[] fieldsIsNull) { if(null != in ){ String postfix = ExcelImport.getpostfix(fileName); if(OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){ return this.analysisXls(in,clazz,fieldsName,fieldsIsNull); }else if(OFFICE_EXCEL_2007_POSTFIX.equals(postfix)){ return this.analysisXlsx(in,clazz,fieldsName,fieldsIsNull); }else { return null; } } return null; }
/**
* 获取文件后缀名 * @param path * @return */ public static String getpostfix(String path){ if(path == null || EMPTY.equals(path.trim())){ return ""; } if(path.contains(POINT)){ return path.substring(path.lastIndexOf(POINT)+1,path.length()); } return ""; }
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
【Nacos系列第三篇】- Nacos之Spring Boot Config
作者:毕来生 前言 个人比较看好Spring Cloud Alibaba家族。此系列以Nacos为主题,从Spring、Spring boot、Spring Cloud多个方面逐步进行演示,源码解读。目前来看官方文档还有待完善。网络上除了官网外缺少Nacos系列文章。都是零零散散的知识点。如此系列文章哪里写的有不周全,错误之处。欢迎大家指正。谢谢。 因公众号排版问题,可能会有代码显示不完整,请使用电脑版微信内置浏览器/复制链接到浏览器中。 第一篇 : 【Nacos系列第一篇】-Nacos之Spring Discovery 以及Config。 第二篇 : 【Nacos系列第二篇】-Nacos之Spring Boot Discovery。 因大家在工作中逐步以Spring boot、Spring Cloud为主进行开发。我们接下来会以这两个为核心演示详解。 Nacos架构图 工程结构 上面说了那么多,现在先来看一下我们的Spring boot Nacos config工程结构(Windows下演示) Spring Boot版本:2.1.2.RELEASE 准备工作 1、...
- 下一篇
数据库异常 :java.sql.SQLException: Access denied for user 'root'@'localhost...
一个很初级的异常,各位大大轻拍(括弧笑) 最近在新项目中突然出现了 java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)异常, 从网上找了好多解决办法:改数据库密码,重装数据库了,清楚缓存等等,结果都不行。 先哭三秒 最后发现不是数据库问题,囧一个。原因在项目的数据库配置文件中:初始文件是这样的 修改后是这样滴: 只需要在库后面加上这行代码就OK useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 瞬间感觉人间充满了爱啊。 注:一开始记得查看是不是你本地账号密码错误,或数据库地址错误。
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS7,8上快速安装Gitea,搭建Git服务器
- SpringBoot2全家桶,快速入门学习开发网站教程
- MySQL8.0.19开启GTID主从同步CentOS8
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- 设置Eclipse缩进为4个空格,增强代码规范
- SpringBoot2整合Redis,开启缓存,提高访问速度
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程