zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java读取excel文件并复制(copy)文件到指定目录示例

JAVAExcel文件 示例 目录 读取 指定 复制
2023-06-13 09:15:18 时间

复制代码代码如下:


mportjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.ArrayList;
importjava.util.List;

importorg.apache.log4j.Logger;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;

publicclassDeployByExcel{
 privatestaticLoggerlogger=Logger.getLogger(DeployByExcel.class);

 staticfinalintBUFFER=8192; 


 //Excel
 privateHSSFWorkbookworkbook;

 /**
 *读取Excel文件并将文件列表放到list中
 *@paramsheetNumber
 *@paramdirexcel文件所在目录
 *@return
 *@throwsFileNotFoundException
 *@throwsIOException
 */
 publicList<String>getDatasInSheet(intsheetNumber,Filedir)throwsFileNotFoundException,IOException{

  File[]files=dir.listFiles(); 
  List<String>result=newArrayList<String>();
       for(Filef:files)
       {
        if(!f.getName().toLowerCase().endsWith(".xls"))
        {
         continue;
        }
        workbook=newHSSFWorkbook(newFileInputStream(f));

   //获得指定的表
   HSSFSheetsheet=workbook.getSheetAt(sheetNumber);
   //获得数据总行数
   introwCount=sheet.getLastRowNum();
   logger.info("foundexcelrowscount:"+rowCount);
   if(rowCount<1){
    returnresult;
   }
   //逐行读取数据
   for(introwIndex=4;rowIndex<=rowCount;rowIndex++){ 
    //获得行对象
    HSSFRowrow=sheet.getRow(rowIndex);
    if(row!=null){
     List<Object>rowData=newArrayList<Object>();
     //获得本行中单元格的个数
     intcolumnCount=row.getLastCellNum();
     //获得本行中各单元格中的数据
     HSSFCellcell=row.getCell(1);
     //获得指定单元格中数据
     Stringstr=(String)this.getCellString(cell);
     if(str!=null&&str.length()>1)
      result.add(str);
    }
   }
       }
  returnresult;
 }


 privatevoidcopy(StringsourcePath,StringdestPath,List<String>fileList,StringwebContent)throwsIOException{
  intnum=1;
  for(Stringstr:fileList){
   str=str.replace(".java",".class");
   if(str.indexOf("/")!=-1){

    if(str.indexOf("src")==0){
     str=str.replace("src","WEB-INF/classes");
    }elseif(str.toUpperCase().indexOf(webContent.toUpperCase())==0){
     str=str.replace(webContent+"/","");
    }

    
    booleanf=copyFile(str,sourcePath,destPath);
    if(f)
    {
     logger.info("Thefileis:"+num);
     num++;

     StringfileName1=str;
     intn=1;
     while(fileName1.endsWith(".class"))
     {
      str=fileName1.replace(".class","$"+n+".class");
      if(!copyFile(str,sourcePath,destPath))
      {
       break;
      }
      n++;
     }
    }
   }
  }
 }
 /**
 *copystrtodestPath
 *
 *@paramstr
 *@paramsourcePath
 *@paramdestPath
 *@returnbooleanisFilereturntrue;elsereturnfalse;
 *@throwsIOException
 */
 privatebooleancopyFile(Stringstr,StringsourcePath,StringdestPath)throwsIOException
 {
  booleanf=false;
  StringdestFilePath=destPath+str;
  StringsourceFilePath=sourcePath+str;
  FilenewDir=newFile(destFilePath.substring(0,destFilePath.lastIndexOf("/")));
  FilesourceFile=newFile(sourceFilePath.trim());
  if(!sourceFile.exists())
  {
   returnf;
  }
  logger.info("dest:"+destFilePath+"    "+"source:"+sourceFilePath);
  FiledestFile=newFile(destFilePath.trim());
  if(!newDir.exists()){
   newDir.mkdirs();
  }
  if(!sourceFile.isDirectory())
  {
   InputStreamin=newFileInputStream(sourceFile);
   FileOutputStreamout=newFileOutputStream(destFile);
   byte[]buffer=newbyte[1024];
   intins;
   while((ins=in.read(buffer))!=-1){
    out.write(buffer,0,ins);
   }
   in.close();
   out.flush();
   out.close();
   f=true;
  }
  returnf;

 }
 /**
 *获得单元格中的内容
 *@paramcell
 *@return
 */
 protectedObjectgetCellString(HSSFCellcell){
  Objectresult=null;
    if(cell!=null){
     intcellType=cell.getCellType();
     switch(cellType){
      caseHSSFCell.CELL_TYPE_STRING:
       result=cell.getRichStringCellValue().getString();
       break;
      caseHSSFCell.CELL_TYPE_NUMERIC:
       result=cell.getNumericCellValue();
       break;
      caseHSSFCell.CELL_TYPE_FORMULA:
       result=cell.getNumericCellValue();
       break;
      caseHSSFCell.CELL_TYPE_ERROR:
       result=null;
       break;
      caseHSSFCell.CELL_TYPE_BOOLEAN:
       result=cell.getBooleanCellValue();
       break;
      caseHSSFCell.CELL_TYPE_BLANK:
       result=null;
       break;
     }
    }
    returnresult;
 }
  

 /**
 *
 *@paramargsargs[0]:Excel文件所在目录;args[1]:源目录(编译后的文件目录);args[2]:发布目录
 *@throwsException
 */
 publicstaticvoidmain(String[]args)throwsException{

  if(args==null||args.length<3)
  {
   logger.info("fileisnotfind;");

   logger.fatal("javacn.id5.deploy.DeployByExcel$0$1$2$3\n$0:Excel文件所在目录;$1:源目录(编译后的文件目录);$2:发布目录;$3:jsp所在目录(默认为webContent,可空)\nexiting.");
   System.exit(0);
  }

   Filefile=newFile(args[0]);
   DeployByExceldeploy=newDeployByExcel();
   List<String>fileList=deploy.getDatasInSheet(0,file);
   StringclassPath=args[1];
   StringdestPath=args[2];
   StringwebContent=(args.length>3&&args[3]!=null&&args[3].length()>1)?args[3]:"WebContent";
   deploy.copy(classPath,destPath,fileList,webContent);
   ///tmp/gboss/media/terry/doc/Project_ID5/gboss/WebContent/

 }

}