EXCEL导入功能java代码实现

来源:互联网 发布:如何开通淘宝客赚钱 编辑:程序博客网 时间:2024/05/20 11:27
 

public void importOrganizationPage(File filePath){
  //判断文件是否为EXCEL文件
  String strFile = filePath.getName();
  if(!strFile.substring(strFile.lastIndexOf('.') + 1, strFile.lastIndexOf('.') + 5).equalsIgnoreCase("xlsx")
    && !strFile.substring(strFile.lastIndexOf('.') + 1, strFile.lastIndexOf('.') + 4).equalsIgnoreCase("xls")){
   throw new BusinessException("this.file.error");
  }
  //读取文件
  Workbook workbook = null;
  Sheet sheet = null;
  
  try{
   workbook = workbook.getWorkbook(new FileInputStream(filePath));
//   workbook.getNumberOfSheets(); //返回EXCEL中有几个
   sheet = workbook.getSheet(0);
 
  }
  catch(Exception e){
   e.printStackTrace();
   throw new BusinessException("read the file find Exception");
  }
  
  int allRow = sheet.getRows() - 1;
  StringBuffer message = new StringBuffer();
  List<WmsOrganization> wmsOrganizationList = new ArrayList<WmsOrganization>(1000); //用于装WmsOrganization对象
  int errorCount = 0;//错误条数
  
  for(int row = 1 ; row < sheet.getRows() ; row++){

   //判断必填单元格是否为空
   boolean isEmp = false ;
   for(int line = 0 ; line < 2 ; line ++ ){
    if(StringUtils.isEmpty(sheet.getCell(line,row).getContents().trim()) || sheet.getCell(line,row) == null){
     message.append(row + " 行,"+ line + " 列,不能为空;\n");
     errorCount ++ ;
     isEmp = true ;
    }
   }
   if(isEmp){
    continue;
   }
   
   //插入数据
   WmsOrganization organization = EntityFactory.getEntity(WmsOrganization.class);
   organization.setCode(sheet.getCell(0, row).getContents().trim());
   organization.setName(sheet.getCell(1, row).getContents().trim());
   boolean beData = false;
  
   //读取下面四个boolean类型的数据,并赋值;

原创粉丝点击