欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-24 15:56:34
复制代码 代码如下:mport java.io.file;import java.io.fileinputstream;import java.io.filenotfoun...

复制代码 代码如下:

mport java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.arraylist;
import java.util.list;

import org.apache.log4j.logger;
import org.apache.poi.hssf.usermodel.hssfcell;
import org.apache.poi.hssf.usermodel.hssfrow;
import org.apache.poi.hssf.usermodel.hssfsheet;
import org.apache.poi.hssf.usermodel.hssfworkbook;

public class deploybyexcel {
 private static logger logger= logger.getlogger(deploybyexcel.class);

 static final int buffer = 8192; 


 //excel
 private hssfworkbook workbook ;

 /**
  * 读取excel文件并将文件列表放到list中
  * @param sheetnumber
  * @param dir excel文件所在目录
  * @return
  * @throws filenotfoundexception
  * @throws ioexception
  */
 public list<string> getdatasinsheet(int sheetnumber,file dir) throws filenotfoundexception, ioexception{

  file[] files = dir.listfiles(); 
  list<string> result = new arraylist<string>();
        for(file f : files)
        {
         if(!f.getname().tolowercase().endswith(".xls"))
         {
          continue;
         }
         workbook = new hssfworkbook(new fileinputstream(f));

   //获得指定的表
   hssfsheet sheet = workbook.getsheetat(sheetnumber);
   //获得数据总行数
   int rowcount = sheet.getlastrownum();
   logger.info("found excel rows count: " + rowcount);
   if (rowcount < 1) {
    return result;
   }
   //逐行读取数据
   for (int rowindex = 4; rowindex <= rowcount; rowindex++) { 
    //获得行对象
    hssfrow row = sheet.getrow(rowindex);
    if (row != null) {
     list<object> rowdata = new arraylist<object>();
     //获得本行中单元格的个数
     int columncount = row.getlastcellnum();
     //获得本行中各单元格中的数据
     hssfcell cell = row.getcell(1);
     //获得指定单元格中数据
     string str = (string)this.getcellstring(cell);
     if (str!=null && str.length()>1)
      result.add(str);
    }
   }
        }
  return result;
 }


 private void copy(string sourcepath,string destpath,list<string> filelist,string webcontent) throws ioexception{
  int num =1 ;
  for (string str : filelist){
   str = str.replace(".java", ".class");
   if (str.indexof("/")!=-1){

    if (str.indexof("src")==0){
     str = str.replace("src", "web-inf/classes");
    }else if (str.touppercase().indexof(webcontent.touppercase())==0){
     str = str.replace(webcontent+"/", "");
    }

    
    boolean f = copyfile(str,sourcepath,destpath);
    if(f)
    {
     logger.info("the file is:" + num);
     num ++;

     string filename1 = str;
     int n = 1;
     while(filename1.endswith(".class"))
     {
      str = filename1.replace(".class", "$" + n +".class");
      if(!copyfile(str,sourcepath,destpath))
      {
       break;
      }
      n ++;
     }
    }
   }
  }
 }
 /**
  * copy str to destpath
  *
  * @param str
  * @param sourcepath
  * @param destpath
  * @return boolean isfile return true;else return false;
  * @throws ioexception
  */
 private boolean copyfile(string str,string sourcepath,string destpath) throws ioexception
 {
  boolean f = false;
  string destfilepath = destpath+str;
  string sourcefilepath = sourcepath+str;
  file newdir = new file(destfilepath.substring(0,destfilepath.lastindexof('/')));
  file sourcefile = new file(sourcefilepath.trim());
  if(!sourcefile.exists())
  {
   return f;
  }
  logger.info("dest:"+destfilepath+"     "+"source:"+sourcefilepath);
  file destfile = new file(destfilepath.trim());
  if (!newdir.exists()){
   newdir.mkdirs();
  }
  if(!sourcefile.isdirectory())
  {
   inputstream in=new fileinputstream(sourcefile);
   fileoutputstream out=new fileoutputstream(destfile);
   byte[] buffer=new byte[1024];
   int ins;
   while((ins=in.read(buffer))!=-1){
    out.write(buffer,0,ins);
   }
   in.close();
   out.flush();
   out.close();
   f = true;
  }
  return f;

 }
 /**
 * 获得单元格中的内容
 * @param cell
 * @return
 */
 protected object getcellstring(hssfcell cell){
  object result = null;
     if (cell != null) {
      int celltype = cell.getcelltype();
      switch(celltype){
       case hssfcell.cell_type_string :
        result = cell.getrichstringcellvalue().getstring();
        break;
       case hssfcell.cell_type_numeric:
        result=cell.getnumericcellvalue();
        break;
       case hssfcell.cell_type_formula:
        result = cell.getnumericcellvalue();
        break;
       case hssfcell.cell_type_error:
        result=null;
        break;
       case hssfcell.cell_type_boolean:
        result=cell.getbooleancellvalue();
        break;
       case hssfcell.cell_type_blank:
        result=null;
        break;
      }
     }
     return result;
 }
  

 /**
  *
  * @param args args[0]:excel文件所在目录;args[1]:源目录(编译后的文件目录);args[2]:发布目录
  * @throws exception
  */
 public static void main(string[] args) throws exception {

  if(args == null || args.length <3 )
  {
   logger.info("file is not find;");

   logger.fatal("java cn.id5.deploy.deploybyexcel $0 $1 $2 $3 \n$0:excel文件所在目录;$1:源目录(编译后的文件目录);$2:发布目录;$3:jsp所在目录(默认为webcontent,可空)\nexiting.");
   system.exit(0);
  }

    file file = new file(args[0]);
    deploybyexcel deploy = new deploybyexcel();
    list<string> filelist = deploy.getdatasinsheet(0,file);
    string classpath = args[1];
    string destpath = args[2];
    string webcontent = (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/

 }

}