TestImportExcel.java
- package com.test;
- import com.util.ExcelAnnotation;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.Row;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import java.io.File;
- import java.io.FileInputStream;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.lang.reflect.Type;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * Created by IntelliJ IDEA.
- * User: CYG
- * Date: 12-3-5
- * Time: 下午4:39
- * To change this template use File | Settings | File Templates.
- */
- public class TestImportExcel extends HibernateDaoSupport {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- public Collection impExcel(String className, File file, String... pattern) throws Exception {
- Collection classList = new ArrayList();//解析后每条PatrolGps数据
- Class clazz = Class.forName(className);//实例化类
- int exceptionNum = 0;
- try {
- /**
- * 类反射得到调用方法
- */
- Field filed[] = clazz.getDeclaredFields();
- // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
- Map fieldMap = new HashMap();
- // 循环读取所有字段
- for (int i = 0; i < filed.length; i++) {
- Field f = filed[i];
- // 得到单个字段上的Annotation
- ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
- // 如果标识了Annotationd的话
- if (exa != null) {
- // 构造设置了Annotation的字段的Setter方法
- String fieldName = f.getName();
- String setMethodName = "set"
- + fieldName.substring(0, 1).toUpperCase()
- + fieldName.substring(1);
- // 构造调用的method,
- Method setMethod = clazz.getMethod(setMethodName,
- new Class[] { f.getType() });
- // 将这个method以Annotaion的名字为key来存入。
- fieldMap.put(exa.exportName(), setMethod);//注释的名称对应字段的set方法
- fieldMap.put(exa.exportName()+"_exa", exa);//注释的名称拼接_exa对应字段的注释
- }
- }
- /**
- * excel的解析开始
- */
- // 将传入的File构造为FileInputStream;
- FileInputStream in = new FileInputStream(file);
- // 得到工作表
- HSSFWorkbook book = new HSSFWorkbook(in);
- // 得到第一页
- HSSFSheet sheet = book.getSheetAt(0);
- // 得到第一面的所有行
- Iterator<Row> allRows = sheet.rowIterator();
- /**
- * 标题解析
- */
- // 得到第一行,也就是标题行
- Row title = allRows.next();
- // 得到第一行的所有列
- Iterator<Cell> cellTitle = title.cellIterator();
- // 将标题的文字内容放入到一个map中。
- Map titleMap = new HashMap();
- int i=0;
- while (cellTitle.hasNext()) {
- Cell cell = cellTitle.next();
- String value = cell.getStringCellValue();
- titleMap.put(i, value);
- i = i + 1;
- }
- // 判断标题栏是否为空
- if(fieldMap.get(titleMap.get(0))==null){
- exceptionNum = 3;
- throw new Exception();
- }
- /**
- * 解析内容行
- */
- // 用来格式化日期的DateFormat
- if(pattern.length>=1)
- {
- sdf=new SimpleDateFormat(pattern[0]);
- }
- int j = 0;//行数
- int k = 0;//列数
- try{
- while(allRows.hasNext()){
- // 标题下的第一行
- Row nextRow = allRows.next();
- // 得到传入类的实例
- Object objClass = clazz.newInstance();
- // 遍历一行的列,每行开始初始化列数
- for (k=0;k<titleMap.size();k++){
- // 列取值
- Cell cell = nextRow.getCell(k);
- // 这里得到此列对应的标题
- String titleString = titleMap.get(k).toString();
- // 如果这一列的标题和类中的某一列的Annotation相同,那么就调用此类的set方法进行赋值
- if(fieldMap.containsValue(titleString)){
- Method setMethod = (Method)fieldMap.get(titleString);
- ExcelAnnotation annotation = (ExcelAnnotation)fieldMap.get(titleString+"_exa");
- // 得到setter方法的参数
- Type[] setterTypes = setMethod.getGenericParameterTypes();
- // setter方法只有一个参数
- String parType = setterTypes[0].toString();
- // 取得参数的类型保存到一个字符串里面
- String typeString = "";
- if(null != cell){//当前单元格不为空
- if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){
- java.text.DecimalFormat formatter = new DecimalFormat("#");
- typeString = formatter.format(cell.getNumericCellValue());
- }else if(cell.getCellType() == cell.CELL_TYPE_STRING){
- typeString = String.valueOf(cell.getStringCellValue());
- }else if(cell.getCellType() == cell.CELL_TYPE_FORMULA){
- typeString = String.valueOf(cell.getDateCellValue());
- }else if(cell.getCellType() == cell.CELL_TYPE_BLANK){
- typeString = String.valueOf(cell.getStringCellValue());
- }else if(cell.getCellType() == cell.CELL_TYPE_ERROR){
- typeString = "";
- }
- }
- if(parType.equals("class java.lang.String")){
- setMethod.invoke(objClass,typeString);
- }else if(parType.equals("class java.util.Date")){
- if(null!=typeString && !"".equals(typeString.trim()))
- setMethod.invoke(objClass,sdf.format(typeString.trim()));
- }else if(parType.equals("class java.lang.Boolean")){
- Boolean b = false;
- if(typeString.trim().equals("是")){
- b = true;
- }
- setMethod.invoke(objClass,b);
- }else if(parType.equals("class java.lang.Integer")){
- setMethod.invoke(objClass,new Integer(typeString.trim()));
- }else if(parType.equals("class java.lang.Long")){
- if(null != typeString && !"".equals(typeString.trim()))
- setMethod.invoke(objClass,new Long(typeString));
- else
- setMethod.invoke(objClass,-1L);
- }else if(parType.equals("class java.lang.Float")){
- if(typeString!=null&&!"".equals(typeString.trim()))
- setMethod.invoke(objClass,new Float(typeString));
- else {
- setMethod.invoke(objClass,new Float(-1));
- }
- }else if(parType.equals("class java.lang.Double")){
- if(typeString!=null&&!"".equals(typeString.trim()))
- setMethod.invoke(objClass,new Double(typeString));
- else {
- setMethod.invoke(objClass,new Double(-1));
- }
- }
- }
- }
- classList.add(objClass);//将这个类保存到List里面
- }
- }catch (Exception e){
- e.printStackTrace();
- if(exceptionNum == 0){
- throw new Exception("第"+(j+1)+"行"+(k+1)+"列出错!请检查!") ;
- }
- }
- }catch (Exception e){
- e.printStackTrace();
- if(exceptionNum == 3){
- throw new Exception("第一行标题栏不正确!") ;
- }
- throw new Exception("导入出错,请检查Excel格式") ;
- }
- return classList;//返回解析成功后List内容
- }
- public void save(String className, File File) throws Exception{
- try {
- Long before = System.currentTimeMillis();
- List obj = (ArrayList)impExcel(className,File);
- Long after = System.currentTimeMillis();
- System.out.println("此次操作共耗时:" + (after - before) + "毫秒");
- if(null != obj)
- for(int i=0;i<obj.size();i++){
- getHibernateTemplate().saveOrUpdate(obj.get(i));
- }
- } catch (Exception e){
- e.printStackTrace();
- throw e;
- }
- }
- }
对于以上测试,自己随便编写一个实体类即可!要注解的。
@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
- package com.util;
- import java.lang.annotation.*;
- public @interface ExcelAnnotation {
- // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入
- public String exportName();
- public String FKEntity() default "";
- public String FKID() default "";
- public String name() default "";
- }