采用的是jxl,所以需要导jxl-2.4.2.jar的jar包.(前提知道excel表的目录):

 

 

   //用log记录异常信息

    private static final Logger log = LoggerFactory.getLogger(NwcfgdmService.class);

 

   //采用spring注解方式调用dao层的查询方法  

    @Autowired  
    private CirCuitBoInf cirCuitBo;

public void excelToDb(){
    Workbook rwb=null;
    FileWriter fw = null;
    try {

      //默认的excel路径为D://opt/BOCO/name.xls
      InputStream is=new FileInputStream(new File("D:"+File.separator+"opt"+File.separator+"BOCO"+File.separator+"name.xls"));//读取文件
      rwb=Workbook.getWorkbook(is);
      Sheet rs=rwb.getSheet(0);
      try {

        //同是将数据库插入出现的异常记录在error.text文件上
        fw = new FileWriter("D:"+File.separator+"opt"+File.separator+"BOCO"+File.separator+"error.text",true);
        // 第二个参数 true 表示写入方式是追加方式
      } catch (Exception e) {
        e.printStackTrace();
        log.error("书写异常日志信息失败",e);
      }
      int rsRows=rs.getRows();
      // System.out.println(rsRows);
      int rsClos=rs.getColumns();
      // System.out.println(rsClos+"----");
      // 因为excel的第一行一般都是实体类的属性。所以从i从1开始取,这样就直接能读取数据了
      for(int i=1;i<rsRows;i++){
        for(int j =0;j<rsClos;j++){
        //默认最左边编号也算一列,所以这里是j++

        //时间的格式默认是yyyy/MM/dd,格式可自定义
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String id=rs.getCell(j++, i).getContents()+"";
        String name=rs.getCell(j++, i).getContents()+"";

        String end_date = rs.getCell(j++, i).getContents();

          Date end_dates = new Date();
        if(! end_date.equals("")){
        try{
          end_dates = sdf.parse(end_time);
        }catch(ParseException e){
          e.printStackTrace();
          log.error("名字为"+name+"的使用期限的格式不对,格式应该为'yyyy/MM/dd'",e);
          fw.write("名字为"+name+"的使用期限的格式不对,格式应该为'yyyy/MM/dd'"+"\r\n");
        }  
       }
        // 接下来就是把从excel读取到的内容逐个set到Person对象中。然后将对象添加到集合。
        Person c =new Person();
        c.setId(id);
        c.setName(name);
        c.setEnd_date(end_dates);
        try {
          cirCuitBo.addCirCuit(c);
        } catch (UncategorizedSQLException e) {
        e.printStackTrace();
          log.error(c.getName()+"这条数据的某个字段长度超出了数据库定义的最大长度",e);
          fw.write(c.getName()+"这条数据的某个字段长度超出了数据库定义的最大长度"+"\r\n");
          // System.out.println("错误信息:"+e+"---------");
        }catch(DataIntegrityViolationException e){
          e.printStackTrace();
          log.error(c.getName()+"这条数据的时间格式不对",e);
          fw.write(c.getName()+"这条数据的时间格式不对"+"\r\n");
        }catch(Exception e){
          e.printStackTrace();
          log.error(c.getName()+"这条数据插入失败",e);
        }
    }
  }
}
    }catch (FileNotFoundException e) {
      e.printStackTrace();
      log.error("该目录下不存在该文件",e);
    }catch(Exception e){
      e.printStackTrace();
      log.error("读取文件失败,请重新操作",e);
    }finally{
      rwb.close();
    try{
      fw.close();
    }catch (IOException e){
    e.printStackTrace();

    log.error("操作失败",e);
}
}
}

posted on 2015-11-20 14:55  田梦伟  阅读(177)  评论(0编辑  收藏  举报