POI遍历Excel

/**
 * 读取Excel文件,并将其内容输出到控制台
 * */

package basic;

import java.io.FileInputStream;

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 POI_ReaderFile
{

 /**
  * @param args
  */
 public static void main(String[] args)
 {
  try
  {
   FileInputStream readFile = new FileInputStream("D://POI_Export//helloworld.xls");
   //创建一个WorkBook,从指定的文件流中创建,即上面指定了的文件流
   HSSFWorkbook wb = new HSSFWorkbook(readFile);
   //获取名称为"测试页"的sheet
   //注意,如果不能确定具体的名称,可以用getSheetAt(int)方法取得Sheet
   //HSSFSheet st = wb.getSheet("测试页");
   //--遍历整个excel
   int sheetCount = wb.getNumberOfSheets();
   for(int i=0;i<sheetCount;i++)
   {
    HSSFSheet sheet = wb.getSheetAt(i);
    int rowNum = sheet.getPhysicalNumberOfRows();
    int cellNum = sheet.getRow(0).getPhysicalNumberOfCells();
    for(int j=0;j<rowNum;j++)
    {
     HSSFRow row = sheet.getRow(j);
     for(short k=0;k<cellNum;k++)
     {
      HSSFCell cell = row.getCell(k);
      if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
      {
       System.out.println(cell.getStringCellValue());
      }
      else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
      {
       System.out.println(cell.getNumericCellValue());
      }
      else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN)
      {
       System.out.println(cell.getBooleanCellValue());
      }
      else if(cell.getCellType() == HSSFCell.CELL_TYPE_BLANK)
      {
       System.out.println("NULL");
      }
      else
      {
       System.out.println(cell.getDateCellValue());
      }
     }
     System.out.println("-----------------------------");
    }
   }
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
  }
 }

}

你可能感兴趣的:(POI遍历Excel)