亲宝软件园·资讯

展开

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

人气:0
想了解java读取excel文件并复制(copy)文件到指定目录示例的相关内容吗,在本文为您仔细讲解java读取excel文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java读取excel文件,指定目录,下面大家一起来学习吧。

复制代码 代码如下:

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/

 }

}

加载全部内容

相关教程
猜你喜欢
用户评论