天天看點

poi解析Excel 支援2003、2007

package com.fh.controller.information.pictures;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class ExcelIn {

	 /**
	   * 讀取出filePath中的所有資料資訊
	   * @param filePath excel檔案的絕對路徑
	   * 
	   */
	  public static  void getDataFromExcel()
	  {
	    String filePath = "E:\\123.xlsx";
	    //判斷是否為excel類型檔案
	   
	    FileInputStream fis =null;
	    FileInputStream fis2 =null;
	    Workbook wookbook = null;
	    try
	    {
	      //擷取一個絕對位址的流
	        fis = new FileInputStream(filePath);
	        fis2 =new FileInputStream(filePath);
	    }
	    catch(Exception e)
	    {
	      e.printStackTrace();
	    }
	    try 
	    {
	      //2003版本的excel,用.xls結尾
	     wookbook = new HSSFWorkbook(fis2);//得到工作簿
	       
	    } 
	    catch (Exception ex) 
	    {
	      //ex.printStackTrace();
	      try
	      {
	        //2007版本的excel,用.xlsx結尾
	        
	        wookbook = new XSSFWorkbook(fis);//得到工作簿
	      } catch (IOException e)
	      {
	        //  Auto-generated catch block
	        e.printStackTrace();
	      }
	    }
	    //得到一個工作表
	    Sheet sheet = wookbook.getSheetAt(0);
	    //獲得表頭
	    Row rowHead = sheet.getRow(0);
	    //獲得資料的總行數
	    int totalRowNum = sheet.getLastRowNum();
	     //獲得所有資料
	    List<String> cus=new ArrayList<String>();
	   
	    for(int i = 0 ; i <= totalRowNum ; i++)
	    {
	      //獲得第i行對象
	      Row row = sheet.getRow(i);
	      for(int j=0;j<=row.getLastCellNum();j++){
	    	  String cu=new String();
	      //獲得獲得第i行第0列的 String類型對象
	      Cell cell = row.getCell((short)j);
	      if(cell!=null)
	       System.out.println( cell.toString());
	      //獲得一個數字類型的資料
	     
	    
	      }
	    }
	  }
	  public static void main(String[] args) {
		  ExcelIn.getDataFromExcel();
	}
}
           

需要導入三個jar包

poi-ooxml-3.5-FINAL.jar

poi-3.5-FINAL.jar

xmlbeans-2.5.0.jar

繼續閱讀