服务器之家

服务器之家 > 正文

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

时间:2019-11-07 12:48     来源/作者:java教程网

代码如下:


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/

 }

}

 

标签:

相关文章

热门资讯

玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情 2019-06-22
Nginx服务器究竟是怎么执行PHP项目
Nginx服务器究竟是怎么执行PHP项目 2019-05-24
配置IIS网站web服务器的安全策略配置解决方案
配置IIS网站web服务器的安全策略配置解决方案 2019-05-23
返回顶部