java poi导入Excel通用工具类

http://blog.csdn.net/daochuwenziyao/article/details/77914826

问题引入和分析

提示:如果不想看罗嗦的文章,可以直接到最后点击源码下载运行即可


最近在做一个导入Excel的功能,在做之前在百度上面查找“java通用导入Excel工具类”,没有查到,大多数都是java通用导出Excel。后来仔细想想,导出可以利用java的反射,做成通用的,放进相应的实体成员变量中,导入为什么不可以呢?也是可以的,不过在做之前我们要解决如下两个问题:

1.表格中的列数和顺序要和实体类中的成员变量个数和顺序一致。

2.表格中的列的类型要和成员变量的类型一致。


第一个问题:

列数一致可以做到,但是我们最后都是要插入数据库的。那么id是必不可少的,或者良好的习惯可能还有创建时间,创建人等信息。

所以我想到了两个办法:

1.封装一个Vo,只将需要的字段封装进去,并且字段顺序和表格列的顺序一致,再将vo与实体类po转化(用PropertyUtil.copy方法);

2.在需要的成员变量上注入自定义注解,并且加入注解的这些字段顺序和表格列的顺序一致,利用反射得到这些字段。

这里主要利用第二个方法,因为扩展性更好


第二个问题:

获取表格数据的时候,我们要判断类型,并取得相应值,全部转化为String类型,当我们给实体类赋值的时候,利用反射获取需要的成员变量的类型,并赋值。


需求

假设我们需求的excel如下:

java poi导入Excel通用工具类


我们可以看做两部分:

第一部分:

第二行到第11行,为一个列表数据,共有字段5个,分别为:学号,姓名,身份证号码,性别,分数


第二部分:

第12行第五列,第12行第六列,共有字段2个,分别为:总计,平均



项目

需要导入的jar包

1.poi的相关jar包,主要用来处理excel
2.beanutils 利用反射为成员变量赋值
3.commons-lang String判断非空的方法,可以不用自己判断


如若maven项目导入下面的jar包

[html] view plain copy
 print?
  1. <!-- poi操作excel -->  
  2.         <dependency>  
  3.             <groupId>org.apache.poi</groupId>  
  4.             <artifactId>poi-ooxml</artifactId>  
  5.             <version>3.8</version>  
  6.         </dependency>  
  7.         <dependency>  
  8.             <groupId>org.apache.poi</groupId>  
  9.             <artifactId>poi</artifactId>  
  10.             <version>3.8</version>  
  11.         </dependency>  
  12.         <dependency>  
  13.             <groupId>org.apache.poi</groupId>  
  14.             <artifactId>poi-ooxml-schemas</artifactId>  
  15.             <version>3.8</version>  
  16.         </dependency>  
  17. <!-- beanutils -->  
  18.         <dependency>  
  19.             <groupId>commons-beanutils</groupId>  
  20.             <artifactId>commons-beanutils</artifactId>  
  21.             <version>1.8.3</version>  
  22.         </dependency>  
  23. <!-- commons-lang-->  
  24.         <dependency>  
  25.                 <groupId>commons-lang</groupId>  
  26.                 <artifactId>commons-lang</artifactId>  
  27.                 <version>2.6</version>  
  28.         </dependency>  

非maven项目导入下面的jar(下面例子当中用到的jar,有些没用到,可自行处理)

commons-beanutils-1.8.3.jar
commons-lang-2.6.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
log4j-1.2.13.jar
poi-3.8-20120326.jar
poi-excelant-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
stax-api-1.0.1.jar
xmlbeans-2.3.0.jar


项目结构

java poi导入Excel通用工具类



工具类

[java] view plain copy
 print?
  1. package com.dao.chu.excel;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.lang.reflect.Field;  
  6. import java.math.BigDecimal;  
  7. import java.text.DecimalFormat;  
  8. import java.text.ParseException;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.ArrayList;  
  11. import java.util.Date;  
  12. import java.util.List;  
  13. import java.util.Locale;  
  14.   
  15. import org.apache.commons.beanutils.PropertyUtils;  
  16. import org.apache.commons.lang.StringUtils;  
  17. import org.apache.poi.hssf.usermodel.HSSFCell;  
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  19. import org.apache.poi.ss.usermodel.Cell;  
  20. import org.apache.poi.ss.usermodel.Row;  
  21. import org.apache.poi.ss.usermodel.Sheet;  
  22. import org.apache.poi.ss.usermodel.Workbook;  
  23. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  24.   
  25. /** 
  26.  *  
  27.  * excel读取工具类 
  28.  *  
  29.  * @author daochuwenziyao 
  30.  * @see [相关类/方法] 
  31.  * @since [产品/模块版本] 
  32.  */  
  33. public class ImportExeclUtil  
  34. {  
  35.       
  36.     private static int totalRows = 0;// 总行数  
  37.       
  38.     private static int totalCells = 0;// 总列数  
  39.       
  40.     private static String errorInfo;// 错误信息  
  41.       
  42.     /** 无参构造方法 */  
  43.     public ImportExeclUtil()  
  44.     {  
  45.     }  
  46.       
  47.     public static int getTotalRows()  
  48.     {  
  49.         return totalRows;  
  50.     }  
  51.       
  52.     public static int getTotalCells()  
  53.     {  
  54.         return totalCells;  
  55.     }  
  56.       
  57.     public static String getErrorInfo()  
  58.     {  
  59.         return errorInfo;  
  60.     }  
  61.       
  62.     /** 
  63.      *  
  64.      * 根据流读取Excel文件 
  65.      *  
  66.      *  
  67.      * @param inputStream 
  68.      * @param isExcel2003 
  69.      * @return 
  70.      * @see [类、类#方法、类#成员] 
  71.      */  
  72.     public List<List<String>> read(InputStream inputStream, boolean isExcel2003)  
  73.         throws IOException  
  74.     {  
  75.           
  76.         List<List<String>> dataLst = null;  
  77.           
  78.         /** 根据版本选择创建Workbook的方式 */  
  79.         Workbook wb = null;  
  80.           
  81.         if (isExcel2003)  
  82.         {  
  83.             wb = new HSSFWorkbook(inputStream);  
  84.         }  
  85.         else  
  86.         {  
  87.             wb = new XSSFWorkbook(inputStream);  
  88.         }  
  89.         dataLst = readDate(wb);  
  90.           
  91.         return dataLst;  
  92.     }  
  93.       
  94.     /** 
  95.      *  
  96.      * 读取数据 
  97.      *  
  98.      * @param wb 
  99.      * @return 
  100.      * @see [类、类#方法、类#成员] 
  101.      */  
  102.     private List<List<String>> readDate(Workbook wb)  
  103.     {  
  104.           
  105.         List<List<String>> dataLst = new ArrayList<List<String>>();  
  106.           
  107.         /** 得到第一个shell */  
  108.         Sheet sheet = wb.getSheetAt(0);  
  109.           
  110.         /** 得到Excel的行数 */  
  111.         totalRows = sheet.getPhysicalNumberOfRows();  
  112.           
  113.         /** 得到Excel的列数 */  
  114.         if (totalRows >= 1 && sheet.getRow(0) != null)  
  115.         {  
  116.             totalCells = sheet.getRow(0).getPhysicalNumberOfCells();  
  117.         }  
  118.           
  119.         /** 循环Excel的行 */  
  120.         for (int r = 0; r < totalRows; r++)  
  121.         {  
  122.             Row row = sheet.getRow(r);  
  123.             if (row == null)  
  124.             {  
  125.                 continue;  
  126.             }  
  127.               
  128.             List<String> rowLst = new ArrayList<String>();  
  129.               
  130.             /** 循环Excel的列 */  
  131.             for (int c = 0; c < getTotalCells(); c++)  
  132.             {  
  133.                   
  134.                 Cell cell = row.getCell(c);  
  135.                 String cellValue = "";  
  136.                   
  137.                 if (null != cell)  
  138.                 {  
  139.                     // 以下是判断数据的类型  
  140.                     switch (cell.getCellType())  
  141.                     {  
  142.                         case HSSFCell.CELL_TYPE_NUMERIC: // 数字  
  143.                             cellValue = cell.getNumericCellValue() + "";  
  144.                             break;  
  145.                           
  146.                         case HSSFCell.CELL_TYPE_STRING: // 字符串  
  147.                             cellValue = cell.getStringCellValue();  
  148.                             break;  
  149.                           
  150.                         case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
  151.                             cellValue = cell.getBooleanCellValue() + "";  
  152.                             break;  
  153.                           
  154.                         case HSSFCell.CELL_TYPE_FORMULA: // 公式  
  155.                             cellValue = cell.getCellFormula() + "";  
  156.                             break;  
  157.                           
  158.                         case HSSFCell.CELL_TYPE_BLANK: // 空值  
  159.                             cellValue = "";  
  160.                             break;  
  161.                           
  162.                         case HSSFCell.CELL_TYPE_ERROR: // 故障  
  163.                             cellValue = "非法字符";  
  164.                             break;  
  165.                           
  166.                         default:  
  167.                             cellValue = "未知类型";  
  168.                             break;  
  169.                     }  
  170.                 }  
  171.                   
  172.                 rowLst.add(cellValue);  
  173.             }  
  174.               
  175.             /** 保存第r行的第c列 */  
  176.             dataLst.add(rowLst);  
  177.         }  
  178.           
  179.         return dataLst;  
  180.     }  
  181.       
  182.     /** 
  183.      *  
  184.      * 按指定坐标读取实体数据 
  185.      * <按顺序放入带有注解的实体成员变量中> 
  186.      *  
  187.      * @param wb 工作簿 
  188.      * @param t 实体 
  189.      * @param in 输入流 
  190.      * @param integers 指定需要解析的坐标 
  191.      * @return T 相应实体 
  192.      * @throws IOException 
  193.      * @throws Exception 
  194.      * @see [类、类#方法、类#成员] 
  195.      */  
  196.     @SuppressWarnings("unused")  
  197.     public static <T> T readDateT(Workbook wb, T t, InputStream in, Integer[]... integers)  
  198.         throws IOException, Exception  
  199.     {  
  200.         // 获取该工作表中的第一个工作表  
  201.         Sheet sheet = wb.getSheetAt(0);  
  202.           
  203.         // 成员变量的值  
  204.         Object entityMemberValue = "";  
  205.           
  206.         // 所有成员变量  
  207.         Field[] fields = t.getClass().getDeclaredFields();  
  208.         // 列开始下标  
  209.         int startCell = 0;  
  210.           
  211.         /** 循环出需要的成员 */  
  212.         for (int f = 0; f < fields.length; f++)  
  213.         {  
  214.               
  215.             fields[f].setAccessible(true);  
  216.             String fieldName = fields[f].getName();  
  217.             boolean fieldHasAnno = fields[f].isAnnotationPresent(IsNeeded.class);  
  218.             // 有注解  
  219.             if (fieldHasAnno)  
  220.             {  
  221.                 IsNeeded annotation = fields[f].getAnnotation(IsNeeded.class);  
  222.                 boolean isNeeded = annotation.isNeeded();  
  223.                   
  224.                 // Excel需要赋值的列  
  225.                 if (isNeeded)  
  226.                 {  
  227.                       
  228.                     // 获取行和列  
  229.                     int x = integers[startCell][0] - 1;  
  230.                     int y = integers[startCell][1] - 1;  
  231.                       
  232.                     Row row = sheet.getRow(x);  
  233.                     Cell cell = row.getCell(y);  
  234.                       
  235.                     if (row == null)  
  236.                     {  
  237.                         continue;  
  238.                     }  
  239.                       
  240.                     // Excel中解析的值  
  241.                     String cellValue = getCellValue(cell);  
  242.                     // 需要赋给成员变量的值  
  243.                     entityMemberValue = getEntityMemberValue(entityMemberValue, fields, f, cellValue);  
  244.                     // 赋值  
  245.                     PropertyUtils.setProperty(t, fieldName, entityMemberValue);  
  246.                     // 列的下标加1  
  247.                     startCell++;  
  248.                 }  
  249.             }  
  250.               
  251.         }  
  252.           
  253.         return t;  
  254.     }  
  255.       
  256.     /** 
  257.      *  
  258.      * 读取列表数据  
  259.      * <按顺序放入带有注解的实体成员变量中> 
  260.      *  
  261.      * @param wb 工作簿 
  262.      * @param t 实体 
  263.      * @param beginLine 开始行数 
  264.      * @param totalcut 结束行数减去相应行数 
  265.      * @return List<T> 实体列表 
  266.      * @throws Exception 
  267.      * @see [类、类#方法、类#成员] 
  268.      */  
  269.     @SuppressWarnings("unchecked")  
  270.     public static <T> List<T> readDateListT(Workbook wb, T t, int beginLine, int totalcut)  
  271.         throws Exception  
  272.     {  
  273.         List<T> listt = new ArrayList<T>();  
  274.           
  275.         /** 得到第一个shell */  
  276.         Sheet sheet = wb.getSheetAt(0);  
  277.           
  278.         /** 得到Excel的行数 */  
  279.         totalRows = sheet.getPhysicalNumberOfRows();  
  280.           
  281.         /** 得到Excel的列数 */  
  282.         if (totalRows >= 1 && sheet.getRow(0) != null)  
  283.         {  
  284.             totalCells = sheet.getRow(0).getPhysicalNumberOfCells();  
  285.         }  
  286.           
  287.         /** 循环Excel的行 */  
  288.         for (int r = beginLine - 1; r < totalRows - totalcut; r++)  
  289.         {  
  290.             Object newInstance = t.getClass().newInstance();  
  291.             Row row = sheet.getRow(r);  
  292.             if (row == null)  
  293.             {  
  294.                 continue;  
  295.             }  
  296.               
  297.             // 成员变量的值  
  298.             Object entityMemberValue = "";  
  299.               
  300.             // 所有成员变量  
  301.             Field[] fields = t.getClass().getDeclaredFields();  
  302.             // 列开始下标  
  303.             int startCell = 0;  
  304.               
  305.             for (int f = 0; f < fields.length; f++)  
  306.             {  
  307.                   
  308.                 fields[f].setAccessible(true);  
  309.                 String fieldName = fields[f].getName();  
  310.                 boolean fieldHasAnno = fields[f].isAnnotationPresent(IsNeeded.class);  
  311.                 // 有注解  
  312.                 if (fieldHasAnno)  
  313.                 {  
  314.                     IsNeeded annotation = fields[f].getAnnotation(IsNeeded.class);  
  315.                     boolean isNeeded = annotation.isNeeded();  
  316.                     // Excel需要赋值的列  
  317.                     if (isNeeded)  
  318.                     {  
  319.                         Cell cell = row.getCell(startCell);  
  320.                         String cellValue = getCellValue(cell);  
  321.                         entityMemberValue = getEntityMemberValue(entityMemberValue, fields, f, cellValue);  
  322.                         // 赋值  
  323.                         PropertyUtils.setProperty(newInstance, fieldName, entityMemberValue);  
  324.                         // 列的下标加1  
  325.                         startCell++;  
  326.                     }  
  327.                 }  
  328.                   
  329.             }  
  330.               
  331.             listt.add((T)newInstance);  
  332.         }  
  333.           
  334.         return listt;  
  335.     }  
  336.       
  337.     /** 
  338.      *  
  339.      * 根据Excel表格中的数据判断类型得到值 
  340.      *  
  341.      * @param cell 
  342.      * @return 
  343.      * @see [类、类#方法、类#成员] 
  344.      */  
  345.     private static String getCellValue(Cell cell)  
  346.     {  
  347.         String cellValue = "";  
  348.           
  349.         if (null != cell)  
  350.         {  
  351.             // 以下是判断数据的类型  
  352.             switch (cell.getCellType())  
  353.             {  
  354.                 case HSSFCell.CELL_TYPE_NUMERIC: // 数字  
  355.                     if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell))  
  356.                     {  
  357.                         Date theDate = cell.getDateCellValue();  
  358.                         SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");  
  359.                         cellValue = dff.format(theDate);  
  360.                     }  
  361.                     else  
  362.                     {  
  363.                         DecimalFormat df = new DecimalFormat("0");  
  364.                         cellValue = df.format(cell.getNumericCellValue());  
  365.                     }  
  366.                     break;  
  367.                 case HSSFCell.CELL_TYPE_STRING: // 字符串  
  368.                     cellValue = cell.getStringCellValue();  
  369.                     break;  
  370.                   
  371.                 case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
  372.                     cellValue = cell.getBooleanCellValue() + "";  
  373.                     break;  
  374.                   
  375.                 case HSSFCell.CELL_TYPE_FORMULA: // 公式  
  376.                     cellValue = cell.getCellFormula() + "";  
  377.                     break;  
  378.                   
  379.                 case HSSFCell.CELL_TYPE_BLANK: // 空值  
  380.                     cellValue = "";  
  381.                     break;  
  382.                   
  383.                 case HSSFCell.CELL_TYPE_ERROR: // 故障  
  384.                     cellValue = "非法字符";  
  385.                     break;  
  386.                   
  387.                 default:  
  388.                     cellValue = "未知类型";  
  389.                     break;  
  390.             }  
  391.               
  392.         }  
  393.         return cellValue;  
  394.     }  
  395.       
  396.     /** 
  397.      *  
  398.      * 根据实体成员变量的类型得到成员变量的值 
  399.      *  
  400.      * @param realValue 
  401.      * @param fields 
  402.      * @param f 
  403.      * @param cellValue 
  404.      * @return 
  405.      * @see [类、类#方法、类#成员] 
  406.      */  
  407.     private static Object getEntityMemberValue(Object realValue, Field[] fields, int f, String cellValue)  
  408.     {  
  409.         String type = fields[f].getType().getName();  
  410.         switch (type)  
  411.         {  
  412.             case "char":  
  413.             case "java.lang.Character":  
  414.             case "java.lang.String":  
  415.                 realValue = cellValue;  
  416.                 break;  
  417.             case "java.util.Date":  
  418.                 realValue = StringUtils.isBlank(cellValue) ? null : DateUtil.strToDate(cellValue, DateUtil.YYYY_MM_DD);  
  419.                 break;  
  420.             case "java.lang.Integer":  
  421.                 realValue = StringUtils.isBlank(cellValue) ? null : Integer.valueOf(cellValue);  
  422.                 break;  
  423.             case "int":  
  424.             case "float":  
  425.             case "double":  
  426.             case "java.lang.Double":  
  427.             case "java.lang.Float":  
  428.             case "java.lang.Long":  
  429.             case "java.lang.Short":  
  430.             case "java.math.BigDecimal":  
  431.                 realValue = StringUtils.isBlank(cellValue) ? null : new BigDecimal(cellValue);  
  432.                 break;  
  433.             default:  
  434.                 break;  
  435.         }  
  436.         return realValue;  
  437.     }  
  438.       
  439.     /** 
  440.      *  
  441.      * 根据路径或文件名选择Excel版本 
  442.      *  
  443.      *  
  444.      * @param filePathOrName 
  445.      * @param in 
  446.      * @return 
  447.      * @throws IOException 
  448.      * @see [类、类#方法、类#成员] 
  449.      */  
  450.     public static Workbook chooseWorkbook(String filePathOrName, InputStream in)  
  451.         throws IOException  
  452.     {  
  453.         /** 根据版本选择创建Workbook的方式 */  
  454.         Workbook wb = null;  
  455.         boolean isExcel2003 = ExcelVersionUtil.isExcel2003(filePathOrName);  
  456.           
  457.         if (isExcel2003)  
  458.         {  
  459.             wb = new HSSFWorkbook(in);  
  460.         }  
  461.         else  
  462.         {  
  463.             wb = new XSSFWorkbook(in);  
  464.         }  
  465.           
  466.         return wb;  
  467.     }  
  468.       
  469.     static class ExcelVersionUtil  
  470.     {  
  471.           
  472.         /** 
  473.          *  
  474.          * 是否是2003的excel,返回true是2003 
  475.          *  
  476.          *  
  477.          * @param filePath 
  478.          * @return 
  479.          * @see [类、类#方法、类#成员] 
  480.          */  
  481.         public static boolean isExcel2003(String filePath)  
  482.         {  
  483.             return filePath.matches("^.+\\.(?i)(xls)$");  
  484.               
  485.         }  
  486.           
  487.         /** 
  488.          *  
  489.          * 是否是2007的excel,返回true是2007 
  490.          *  
  491.          *  
  492.          * @param filePath 
  493.          * @return 
  494.          * @see [类、类#方法、类#成员] 
  495.          */  
  496.         public static boolean isExcel2007(String filePath)  
  497.         {  
  498.             return filePath.matches("^.+\\.(?i)(xlsx)$");  
  499.               
  500.         }  
  501.           
  502.     }  
  503.       
  504.     public static class DateUtil  
  505.     {  
  506.           
  507.         // ======================日期格式化常量=====================//  
  508.           
  509.         public static final String YYYY_MM_DDHHMMSS = "yyyy-MM-dd HH:mm:ss";  
  510.           
  511.         public static final String YYYY_MM_DD = "yyyy-MM-dd";  
  512.           
  513.         public static final String YYYY_MM = "yyyy-MM";  
  514.           
  515.         public static final String YYYY = "yyyy";  
  516.           
  517.         public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";  
  518.           
  519.         public static final String YYYYMMDD = "yyyyMMdd";  
  520.           
  521.         public static final String YYYYMM = "yyyyMM";  
  522.           
  523.         public static final String YYYYMMDDHHMMSS_1 = "yyyy/MM/dd HH:mm:ss";  
  524.           
  525.         public static final String YYYY_MM_DD_1 = "yyyy/MM/dd";  
  526.           
  527.         public static final String YYYY_MM_1 = "yyyy/MM";  
  528.           
  529.         /** 
  530.          *  
  531.          * 自定义取值,Date类型转为String类型 
  532.          *  
  533.          * @param date 日期 
  534.          * @param pattern 格式化常量 
  535.          * @return 
  536.          * @see [类、类#方法、类#成员] 
  537.          */  
  538.         public static String dateToStr(Date date, String pattern)  
  539.         {  
  540.             SimpleDateFormat format = null;  
  541.               
  542.             if (null == date)  
  543.                 return null;  
  544.             format = new SimpleDateFormat(pattern, Locale.getDefault());  
  545.               
  546.             return format.format(date);  
  547.         }  
  548.           
  549.         /** 
  550.          * 将字符串转换成Date类型的时间 
  551.          * <hr> 
  552.          *  
  553.          * @param s 日期类型的字符串<br> 
  554.          *            datePattern :YYYY_MM_DD<br> 
  555.          * @return java.util.Date 
  556.          */  
  557.         public static Date strToDate(String s, String pattern)  
  558.         {  
  559.             if (s == null)  
  560.             {  
  561.                 return null;  
  562.             }  
  563.             Date date = null;  
  564.             SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  565.             try  
  566.             {  
  567.                 date = sdf.parse(s);  
  568.             }  
  569.             catch (ParseException e)  
  570.             {  
  571.                 e.printStackTrace();  
  572.             }  
  573.             return date;  
  574.         }  
  575.     }  
  576.       
  577. }  


自定义注解

[java] view plain copy
 print?
  1. import java.lang.annotation.ElementType;  
  2. import java.lang.annotation.Retention;  
  3. import java.lang.annotation.RetentionPolicy;  
  4. import java.lang.annotation.Target;  
  5.   
  6. /** 
  7.  *  
  8.  * 是否需要从解析excel赋值 
  9.  * @author daochuwenziyao 
  10.  * @see  [相关类/方法] 
  11.  * @since  [产品/模块版本] 
  12.  */  
  13. @Retention(value = RetentionPolicy.RUNTIME)  
  14. @Target(value = {ElementType.FIELD})  
  15. public @interface IsNeeded  
  16. {  
  17.       
  18.     /** 
  19.      * 是否需要从解析excel赋值 
  20.      * @return 
  21.      *         true:需要  false:不需要 
  22.      * @see [类、类#方法、类#成员] 
  23.      */  
  24.     boolean isNeeded() default true;  
  25. }  


学生基本信息


[java] view plain copy
 print?
  1. import java.math.BigDecimal;  
  2.   
  3. /** 
  4.  *  
  5.  * 学生基本信息 
  6.  * @author daochuwenziyao 
  7.  * @see  [相关类/方法] 
  8.  * @since  [产品/模块版本] 
  9.  */  
  10. public class StudentBaseInfo  
  11. {  
  12.     private Integer id;  
  13.     @IsNeeded  
  14.     private String no;  
  15.     @IsNeeded  
  16.     private String name;  
  17.     @IsNeeded  
  18.     private String idnum;  
  19.     @IsNeeded  
  20.     private String sex;  
  21.     @IsNeeded  
  22.     private BigDecimal grade;  
  23.       
  24.       
  25.     @Override  
  26.     public String toString()  
  27.     {  
  28.         return "StudentBaseInfo [id=" + id + ", no=" + no + ", name=" + name + ", idnum=" + idnum + ", sex=" + sex  
  29.             + ", grade=" + grade + "]";  
  30.     }  
  31.     public Integer getId()  
  32.     {  
  33.         return id;  
  34.     }  
  35.     public void setId(Integer id)  
  36.     {  
  37.         this.id = id;  
  38.     }  
  39.     public String getNo()  
  40.     {  
  41.         return no;  
  42.     }  
  43.     public void setNo(String no)  
  44.     {  
  45.         this.no = no;  
  46.     }  
  47.     public String getName()  
  48.     {  
  49.         return name;  
  50.     }  
  51.     public void setName(String name)  
  52.     {  
  53.         this.name = name;  
  54.     }  
  55.     public String getSex()  
  56.     {  
  57.         return sex;  
  58.     }  
  59.     public void setSex(String sex)  
  60.     {  
  61.         this.sex = sex;  
  62.     }  
  63.     public String getIdnum()  
  64.     {  
  65.         return idnum;  
  66.     }  
  67.     public void setIdnum(String idnum)  
  68.     {  
  69.         this.idnum = idnum;  
  70.     }  
  71.     public BigDecimal getGrade()  
  72.     {  
  73.         return grade;  
  74.     }  
  75.     public void setGrade(BigDecimal grade)  
  76.     {  
  77.         this.grade = grade;  
  78.     }  
  79.       
  80. }  


学生统计信息

[java] view plain copy
 print?
  1. /** 
  2.  *  
  3.  * 学生统计信息 
  4.  * @author daochuwenziyao 
  5.  * @see  [相关类/方法] 
  6.  * @since  [产品/模块版本] 
  7.  */  
  8. public class StudentStatistics  
  9. {  
  10.     private Integer id;  
  11.     @IsNeeded  
  12.     private BigDecimal totalGrade;  
  13.     @IsNeeded  
  14.     private BigDecimal avgGrade;  
  15.       
  16.     @Override  
  17.     public String toString()  
  18.     {  
  19.         return "StudentStatistics [id=" + id + ", totalGrade=" + totalGrade + ", avgGrade=" + avgGrade + "]";  
  20.     }  
  21.     public Integer getId()  
  22.     {  
  23.         return id;  
  24.     }  
  25.     public void setId(Integer id)  
  26.     {  
  27.         this.id = id;  
  28.     }  
  29.     public BigDecimal getTotalGrade()  
  30.     {  
  31.         return totalGrade;  
  32.     }  
  33.     public void setTotalGrade(BigDecimal totalGrade)  
  34.     {  
  35.         this.totalGrade = totalGrade;  
  36.     }  
  37.     public BigDecimal getAvgGrade()  
  38.     {  
  39.         return avgGrade;  
  40.     }  
  41.     public void setAvgGrade(BigDecimal avgGrade)  
  42.     {  
  43.         this.avgGrade = avgGrade;  
  44.     }  
  45.       
  46. }  


测试类


[java] view plain copy
 print?
  1. package com.dao.chu.excel;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.util.List;  
  9.   
  10.   
  11. import org.apache.poi.ss.usermodel.Workbook;  
  12.   
  13.   
  14. public class TestImportExcel  
  15. {  
  16.       
  17.     public static void main(String[] args) throws IOException, Exception  
  18.     {  
  19.           
  20.         String fileName="student.xlsx";  
  21.         InputStream in = new FileInputStream(new File("excelfile\\student.xlsx"));  
  22.         Workbook wb = ImportExeclUtil.chooseWorkbook(fileName, in);  
  23.         StudentStatistics studentStatistics = new StudentStatistics();  
  24.           
  25.         //读取一个对象的信息  
  26.         StudentStatistics readDateT =  
  27.             ImportExeclUtil.readDateT(wb, studentStatistics, in, new Integer[] {125}, new Integer[] {135});  
  28.         System.out.println(readDateT);  
  29.           
  30.         //读取对象列表的信息  
  31.         StudentBaseInfo studentBaseInfo = new StudentBaseInfo();  
  32.         //第二行开始,到倒数第三行结束(总数减去两行)  
  33.         List<StudentBaseInfo> readDateListT = ImportExeclUtil.readDateListT(wb, studentBaseInfo, 22);  
  34.         System.out.println(readDateListT);  
  35.           
  36.     }  
  37. }  


输出结果

StudentStatistics [id=null, totalGrade=845, avgGrade=84]
[StudentBaseInfo [id=null, no=2012240001, name=张三1, idnum=233314199009062304, sex=男, grade=80], StudentBaseInfo [id=null, no=2012240002, name=张三2, idnum=233314199009062304, sex=男, grade=81], StudentBaseInfo [id=null, no=2012240003, name=张三3, idnum=233314199009062304, sex=男, grade=82], StudentBaseInfo [id=null, no=2012240004, name=张三4, idnum=233314199009062304, sex=男, grade=83], StudentBaseInfo [id=null, no=2012240005, name=张三5, idnum=233314199009062304, sex=男, grade=84], StudentBaseInfo [id=null, no=2012240006, name=张三6, idnum=233314199009062304, sex=男, grade=85], StudentBaseInfo [id=null, no=2012240007, name=张三7, idnum=233314199009062304, sex=男, grade=86], StudentBaseInfo [id=null, no=2012240008, name=张三8, idnum=233314199009062304, sex=男, grade=87], StudentBaseInfo [id=null, no=2012240009, name=张三9, idnum=233314199009062304, sex=男, grade=88], StudentBaseInfo [id=null, no=2012240010, name=张三10, idnum=233314199009062304, sex=男, grade=89]]


源码下载

源码分享给大家,上面提到的都在这里,由于很多的数据类型没有试验到,可能会有些类型有问题,所以希望大家如果遇到问题回复我,我会将其完善。谢谢

http://download.csdn.net/download/daochuwenziyao/9971228