`

java中Exel导入数据

 
阅读更多

TestImportExcel.java

 

 

[java] view plaincopy
 
  1. package com.test;  
  2.   
  3. import com.util.ExcelAnnotation;  
  4. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  6. import org.apache.poi.ss.usermodel.Cell;  
  7. import org.apache.poi.ss.usermodel.Row;  
  8. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.lang.reflect.Field;  
  12. import java.lang.reflect.Method;  
  13. import java.lang.reflect.Type;  
  14. import java.text.DecimalFormat;  
  15. import java.text.SimpleDateFormat;  
  16. import java.util.*;  
  17.   
  18. /** 
  19.  * Created by IntelliJ IDEA. 
  20.  * User: CYG 
  21.  * Date: 12-3-5 
  22.  * Time: 下午4:39 
  23.  * To change this template use File | Settings | File Templates. 
  24.  */  
  25. public class TestImportExcel extends HibernateDaoSupport {  
  26.   
  27.     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  28.   
  29.     public Collection impExcel(String className, File file, String... pattern) throws Exception {  
  30.   
  31.         Collection classList = new ArrayList();//解析后每条PatrolGps数据  
  32.         Class clazz = Class.forName(className);//实例化类  
  33.         int exceptionNum = 0;  
  34.   
  35.         try {  
  36.             /** 
  37.              * 类反射得到调用方法 
  38.              */  
  39.             Field filed[] = clazz.getDeclaredFields();  
  40.             // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中  
  41.             Map fieldMap = new HashMap();  
  42.             // 循环读取所有字段  
  43.             for (int i = 0; i < filed.length; i++) {  
  44.                 Field f = filed[i];  
  45.                 // 得到单个字段上的Annotation  
  46.                 ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);  
  47.                 // 如果标识了Annotationd的话  
  48.                 if (exa != null) {  
  49.                     // 构造设置了Annotation的字段的Setter方法  
  50.                     String fieldName = f.getName();  
  51.                     String setMethodName = "set"  
  52.                             + fieldName.substring(01).toUpperCase()  
  53.                             + fieldName.substring(1);  
  54.                     // 构造调用的method,  
  55.                     Method setMethod = clazz.getMethod(setMethodName,  
  56.                             new Class[] { f.getType() });  
  57.                     // 将这个method以Annotaion的名字为key来存入。  
  58.                     fieldMap.put(exa.exportName(), setMethod);//注释的名称对应字段的set方法  
  59.                     fieldMap.put(exa.exportName()+"_exa", exa);//注释的名称拼接_exa对应字段的注释  
  60.                 }  
  61.             }  
  62.             /** 
  63.              * excel的解析开始 
  64.              */  
  65.             // 将传入的File构造为FileInputStream;  
  66.             FileInputStream in = new FileInputStream(file);  
  67.             // 得到工作表  
  68.             HSSFWorkbook book = new HSSFWorkbook(in);  
  69.             // 得到第一页  
  70.             HSSFSheet sheet = book.getSheetAt(0);  
  71.             // 得到第一面的所有行  
  72.             Iterator<Row> allRows = sheet.rowIterator();  
  73.             /** 
  74.              * 标题解析 
  75.              */  
  76.             // 得到第一行,也就是标题行  
  77.             Row title = allRows.next();  
  78.             // 得到第一行的所有列  
  79.             Iterator<Cell> cellTitle = title.cellIterator();  
  80.             // 将标题的文字内容放入到一个map中。  
  81.             Map titleMap = new HashMap();  
  82.             int i=0;  
  83.             while (cellTitle.hasNext()) {  
  84.                 Cell cell = cellTitle.next();  
  85.                 String value = cell.getStringCellValue();  
  86.                 titleMap.put(i, value);  
  87.                 i = i + 1;  
  88.             }  
  89.             // 判断标题栏是否为空  
  90.             if(fieldMap.get(titleMap.get(0))==null){  
  91.                 exceptionNum = 3;  
  92.                 throw new Exception();  
  93.             }  
  94.             /** 
  95.              * 解析内容行 
  96.              */  
  97.             // 用来格式化日期的DateFormat  
  98.             if(pattern.length>=1)  
  99.             {  
  100.                 sdf=new SimpleDateFormat(pattern[0]);  
  101.             }  
  102.             int j = 0;//行数  
  103.             int k = 0;//列数  
  104.             try{  
  105.                 while(allRows.hasNext()){  
  106.                     // 标题下的第一行  
  107.                     Row nextRow = allRows.next();  
  108.                     // 得到传入类的实例  
  109.                     Object objClass = clazz.newInstance();  
  110.                     // 遍历一行的列,每行开始初始化列数  
  111.                     for (k=0;k<titleMap.size();k++){  
  112.                         // 列取值  
  113.                         Cell cell = nextRow.getCell(k);  
  114.                         // 这里得到此列对应的标题  
  115.                         String titleString = titleMap.get(k).toString();  
  116.                         // 如果这一列的标题和类中的某一列的Annotation相同,那么就调用此类的set方法进行赋值  
  117.                         if(fieldMap.containsValue(titleString)){  
  118.                             Method setMethod = (Method)fieldMap.get(titleString);  
  119.                             ExcelAnnotation annotation = (ExcelAnnotation)fieldMap.get(titleString+"_exa");  
  120.                             // 得到setter方法的参数  
  121.                             Type[] setterTypes = setMethod.getGenericParameterTypes();  
  122.                             // setter方法只有一个参数  
  123.                             String parType = setterTypes[0].toString();  
  124.                             // 取得参数的类型保存到一个字符串里面  
  125.                             String typeString = "";  
  126.                             if(null != cell){//当前单元格不为空  
  127.                                  if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){  
  128.                                      java.text.DecimalFormat formatter = new DecimalFormat("#");  
  129.                                      typeString = formatter.format(cell.getNumericCellValue());  
  130.                                  }else if(cell.getCellType() == cell.CELL_TYPE_STRING){  
  131.                                      typeString = String.valueOf(cell.getStringCellValue());  
  132.                                  }else if(cell.getCellType() == cell.CELL_TYPE_FORMULA){  
  133.                                      typeString = String.valueOf(cell.getDateCellValue());  
  134.                                  }else if(cell.getCellType() == cell.CELL_TYPE_BLANK){  
  135.                                      typeString = String.valueOf(cell.getStringCellValue());  
  136.                                  }else if(cell.getCellType() == cell.CELL_TYPE_ERROR){  
  137.                                      typeString = "";  
  138.                                  }  
  139.                             }  
  140.                             if(parType.equals("class java.lang.String")){  
  141.                                 setMethod.invoke(objClass,typeString);  
  142.                             }else if(parType.equals("class java.util.Date")){  
  143.                                 if(null!=typeString && !"".equals(typeString.trim()))  
  144.                                     setMethod.invoke(objClass,sdf.format(typeString.trim()));  
  145.                             }else if(parType.equals("class java.lang.Boolean")){  
  146.                                 Boolean b = false;  
  147.                                 if(typeString.trim().equals("是")){  
  148.                                     b = true;  
  149.                                 }  
  150.                                 setMethod.invoke(objClass,b);  
  151.                             }else if(parType.equals("class java.lang.Integer")){  
  152.                                 setMethod.invoke(objClass,new Integer(typeString.trim()));  
  153.                             }else if(parType.equals("class java.lang.Long")){  
  154.                                 if(null != typeString && !"".equals(typeString.trim()))  
  155.                                     setMethod.invoke(objClass,new Long(typeString));  
  156.                                 else  
  157.                                     setMethod.invoke(objClass,-1L);  
  158.                             }else if(parType.equals("class java.lang.Float")){  
  159.                                 if(typeString!=null&&!"".equals(typeString.trim()))  
  160.                                     setMethod.invoke(objClass,new Float(typeString));  
  161.                                 else {  
  162.                                     setMethod.invoke(objClass,new Float(-1));  
  163.                                 }  
  164.                             }else if(parType.equals("class java.lang.Double")){  
  165.                                 if(typeString!=null&&!"".equals(typeString.trim()))  
  166.                                     setMethod.invoke(objClass,new Double(typeString));  
  167.                                 else {  
  168.                                     setMethod.invoke(objClass,new Double(-1));  
  169.                                 }  
  170.                             }  
  171.                         }  
  172.                     }  
  173.                     classList.add(objClass);//将这个类保存到List里面  
  174.                 }  
  175.             }catch (Exception e){  
  176.                 e.printStackTrace();  
  177.                 if(exceptionNum == 0){  
  178.                     throw new Exception("第"+(j+1)+"行"+(k+1)+"列出错!请检查!") ;  
  179.                 }  
  180.             }  
  181.         }catch (Exception e){  
  182.             e.printStackTrace();  
  183.             if(exceptionNum == 3){  
  184.                 throw new Exception("第一行标题栏不正确!") ;  
  185.             }  
  186.             throw new Exception("导入出错,请检查Excel格式") ;  
  187.         }  
  188.         return classList;//返回解析成功后List内容  
  189.     }  
  190.   
  191.     public void save(String className, File File) throws Exception{  
  192.         try {  
  193.             Long before = System.currentTimeMillis();  
  194.             List obj = (ArrayList)impExcel(className,File);  
  195.             Long after = System.currentTimeMillis();  
  196.             System.out.println("此次操作共耗时:" + (after - before) + "毫秒");  
  197.             if(null != obj)  
  198.                 for(int i=0;i<obj.size();i++){  
  199.                     getHibernateTemplate().saveOrUpdate(obj.get(i));  
  200.                 }  
  201.         } catch (Exception e){  
  202.             e.printStackTrace();  
  203.             throw e;  
  204.         }  
  205.     }  
  206. }  


对于以上测试,自己随便编写一个实体类即可!要注解的。

 

    @Id
    @SequenceGenerator(name = "SEQ_PATROL_GPS", sequenceName = "SEQ_PATROL_GPS_ID", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PATROL_GPS")
    @Basic(optional = false)
    @Column(name = "GPS_ID", nullable = false, precision = 32, scale = 0)

上面这些是注解ID的,不需要注解导入!

    @Column(name="Excel_NAME",length = 50)
    @ExcelAnnotation(exportName = "Excel名字")

上面注解需要导入的Excel字段!

 

ExcelAnnotation.java

 

 

 

[java] view plaincopy
 
  1. package com.util;  
  2.   
  3. import java.lang.annotation.*;  
  4.   
  5. public @interface ExcelAnnotation {     
  6.     // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入     
  7.     public String exportName();  
  8.     public String FKEntity() default "";  
  9.     public String FKID() default "";  
  10.     public String name() default "";  
  11. }    
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics