程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java讀取excel文件並復制(copy)文件到指定目錄示例

java讀取excel文件並復制(copy)文件到指定目錄示例

編輯: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/

 }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved