java excel上传--poi

悠悠 2022-02-14 16:23 409阅读 0赞

工作中很多批量上传需求不同,每个需求都要写一次批量上传代码,太烦。。决定写一个通用工具,此代码复制即用。需要改进的地方请评论区留言

方法调用传参例子:
上传文件中列的字段对应的是对象的属性
String[] fieldsName = new String[]{“carModelName”,”salePrice”};

此参数是上传文件中列必传字段对应对象的属性
String[] fieldsIsNull = new String[]{“carModelName”};

注:数组属性顺序必须和文件中顺序一样,解析文件时赋值不会赋错字段

  1. public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
  2. public static final String OFFICE_EXCEL_2007_POSTFIX = "xlsx";
  3. public static final String EMPTY = "";
  4. public static final String POINT = ".";

/
**

  1. * 通过反射处理以获得的数据
  2. * @param
  3. */
  4. public T reflectDeal(T className, Cell cell, String fieldName){
  5. Class aClass = null;
  6. try {
  7. aClass = className.getClass();
  8. Field[] declaredFields = aClass.getDeclaredFields();
  9. for (Field field:declaredFields) {
  10. field.setAccessible(true);
  11. String names = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
  12. if(field.getName().equals(fieldName) && field.getType().getName().equals("java.math.BigDecimal")){
  13. aClass.getMethod("set"+names,BigDecimal.class).invoke(className,new BigDecimal(""+cell));
  14. }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.String")){
  15. aClass.getMethod("set"+names,String.class).invoke(className,cell.getStringCellValue().toString());
  16. }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Integer")){
  17. aClass.getMethod("set"+names,Integer.class).invoke(className,cell);
  18. }else if(field.getName().equals(fieldName) && field.getType().getName().equals("java.lang.Double")){
  19. aClass.getMethod("set"+names,Double.class).invoke(className,cell);
  20. }
  21. }
  22. } catch (IllegalAccessException e) {
  23. e.printStackTrace();
  24. } catch (NoSuchMethodException e) {
  25. e.printStackTrace();
  26. } catch (InvocationTargetException e) {
  27. e.printStackTrace();
  28. }
  29. return className;
  30. }
  31. /**
  32. * 本段代码解析xls文件
  33. * @param
  34. */
  35. public List<T> analysisXls(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull) {
  36. int totalrows = 0;
  37. int totalCell = 0;
  38. List<T> list = new ArrayList();
  39. logger.info("==================== 开始解析xls文件 =========================");
  40. //流读取文件
  41. //创建文件
  42. HSSFWorkbook wb = null;
  43. try {
  44. wb = new HSSFWorkbook(in);
  45. //读取页数
  46. for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){
  47. Sheet xs = wb.getSheetAt(num);
  48. if(xs == null){
  49. continue;
  50. }
  51. totalrows = xs.getLastRowNum()+1;
  52. for (int rnum = 1 ; rnum < totalrows ; rnum ++){
  53. boolean flag = false;
  54. T o = null;
  55. try {
  56. o = (T)clazz.newInstance();
  57. } catch (InstantiationException e) {
  58. e.printStackTrace();
  59. } catch (IllegalAccessException e) {
  60. e.printStackTrace();
  61. }
  62. Row row = xs.getRow(rnum);
  63. if(row != null){
  64. totalCell = row.getLastCellNum();
  65. int nullCellNumb = 0;
  66. for (int cnum = 0 ; cnum < totalCell ; cnum ++){
  67. Cell cell = row.getCell(cnum);
  68. if(null == cell){
  69. nullCellNumb++;
  70. if(nullCellNumb>=10){
  71. break;
  72. }
  73. continue;
  74. }
  75. if( cell != null && !"".equals(cell.toString().trim())){
  76. this.reflectDeal(o, cell, fieldsName[cnum]);
  77. }else {
  78. for (int x=0;x<fieldsIsNull.length;x++){
  79. if(fieldsIsNull[x].equals(fieldsName[cnum])){
  80. flag = true;
  81. break;
  82. }
  83. }
  84. }
  85. }
  86. if (flag){
  87. continue;
  88. }
  89. list.add(o);
  90. }else {
  91. return list;
  92. }
  93. }
  94. }
  95. } catch (IOException e) {
  96. e.printStackTrace();
  97. }finally {
  98. try {
  99. in.close();
  100. if(null != wb){
  101. wb.close();
  102. }
  103. } catch (IOException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. return list;
  108. }

/**

  1. * 本段代码解析xlsx文件
  2. * @param
  3. * @param clazz
  4. * @param fieldsName
  5. * @return
  6. */
  7. public List<T> analysisXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String[] fieldsIsNull){
  8. int totalrows = 0;
  9. int totalCell = 0;
  10. List<T> list = new ArrayList();
  11. logger.info("==================== 开始解析xlsx文件 =========================");
  12. //流读取文件
  13. //创建文件
  14. XSSFWorkbook wb = null;
  15. try {
  16. wb = new XSSFWorkbook(OPCPackage.open(in));
  17. //读取页数
  18. for(int num = 0 ; num < wb.getNumberOfSheets() ; num ++){
  19. Sheet xs = wb.getSheetAt(num);
  20. if(xs == null){
  21. continue;
  22. }
  23. totalrows = xs.getLastRowNum()+1;
  24. for (int rnum = 1 ; rnum < totalrows ; rnum ++){
  25. boolean flag = false;
  26. T o = (T)clazz.newInstance();
  27. Row row = xs.getRow(rnum);
  28. if(row != null){
  29. totalCell = row.getLastCellNum();
  30. int nullCellNumb = 0;
  31. for (int cnum = 0 ; cnum < totalCell ; cnum ++){
  32. Cell cell = row.getCell(cnum);
  33. if(null == cell){
  34. nullCellNumb++;
  35. if(nullCellNumb>=10){
  36. break;
  37. }
  38. continue;
  39. }
  40. if( cell != null && !"".equals(cell.toString().trim())){
  41. nullCellNumb = 0;
  42. this.reflectDeal(o, cell, fieldsName[cnum]);
  43. }else {
  44. for (int x=0;x<fieldsIsNull.length;x++){
  45. if(fieldsIsNull[x].equals(fieldsName[cnum])){
  46. flag = true;
  47. break;
  48. }
  49. }
  50. }
  51. }
  52. if (flag){
  53. continue;
  54. }
  55. list.add(o);
  56. }else {
  57. return list;
  58. }
  59. }
  60. }
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. } catch (IllegalAccessException e) {
  64. e.printStackTrace();
  65. } catch (InstantiationException e) {
  66. e.printStackTrace();
  67. } catch (InvalidFormatException e) {
  68. logger.info("======= XSSF创建文件失败 ====");
  69. e.printStackTrace();
  70. }finally {
  71. try {
  72. in.close();
  73. if(null != wb){
  74. wb.close();
  75. }
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. return list;
  81. }

/**

  1. *此段代码区分e'xcel版本,分别调用哪个方法
  2. * @param
  3. * @param clazz
  4. * @param fieldsName
  5. * @return
  6. * @throws IOException
  7. */
  8. public List<T> readxlsAndXlsx(InputStream in,Class<?> clazz,String[] fieldsName,String fileName,String[] fieldsIsNull) {
  9. if(null != in ){
  10. String postfix = ExcelImport.getpostfix(fileName);
  11. if(OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
  12. return this.analysisXls(in,clazz,fieldsName,fieldsIsNull);
  13. }else if(OFFICE_EXCEL_2007_POSTFIX.equals(postfix)){
  14. return this.analysisXlsx(in,clazz,fieldsName,fieldsIsNull);
  15. }else {
  16. return null;
  17. }
  18. }
  19. return null;
  20. }

/**

  1. * 获取文件后缀名
  2. * @param path
  3. * @return
  4. */
  5. public static String getpostfix(String path){
  6. if(path == null || EMPTY.equals(path.trim())){
  7. return "";
  8. }
  9. if(path.contains(POINT)){
  10. return path.substring(path.lastIndexOf(POINT)+1,path.length());
  11. }
  12. return "";
  13. }

发表评论

表情:
评论列表 (有 0 条评论,409人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java excel--poi

    工作中很多批量上传需求不同,每个需求都要写一次批量上传代码,太烦。。决定写一个通用工具,此代码复制即用。需要改进的地方请评论区留言 方法调用传参例子: 上传文件中列的字段