poi讀Excel2003兼容2007總結

 

API:http://poi.apache.org/apidocs/index.html

1、

/**
 * ClassName:ExcelReader.java
 * Author: wenbin.ji
 * CreateTime: Jan 28, 2011 11:16:29 AM
 * Description:Excel數據讀取工具類,POI實現,兼容Excel2003,及Excel2007
 **/
package com.company.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.ss.usermodel.WorkbookFactory;

public class ExcelReader {
  Workbook wb = null;
  List<String[]> dataList = new ArrayList<String[]>(100);
  public ExcelReader(String path){
    try {
      InputStream inp = new FileInputStream(path);
      wb = WorkbookFactory.create(inp);      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (InvalidFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }  
  
  /**
   * 取Excel所有數據,包含header
   * @return  List<String[]>
   */
 public List<String[]> getAllData(int sheetIndex){
    int columnNum = 0;
    Sheet sheet = wb.getSheetAt(sheetIndex);
    if(sheet.getRow(0)!=null){
        columnNum = sheet.getRow(0).getLastCellNum()-sheet.getRow(0).getFirstCellNum();
    }
    if(columnNum>0){
      for(Row row:sheet){ 
          String[] singleRow = new String[columnNum];
          int n = 0;
          for(int i=0;i<columnNum;i++){
             Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
             switch(cell.getCellType()){
               case Cell.CELL_TYPE_BLANK:
                 singleRow[n] = "";
                 break;
               case Cell.CELL_TYPE_BOOLEAN:
                 singleRow[n] = Boolean.toString(cell.getBooleanCellValue());
                 break;
                //數值
               case Cell.CELL_TYPE_NUMERIC:               
                 if(DateUtil.isCellDateFormatted(cell)){
                   singleRow[n] = String.valueOf(cell.getDateCellValue());
                 }else{ 
                   cell.setCellType(Cell.CELL_TYPE_STRING);// 沒有這句的話,碰到Number報錯:Cannot get a text value from a numeric cell
                   String temp = cell.getStringCellValue();
                   //判斷是否包含小數點,如果不含小數點,則以字符串讀取,如果含小數點,則轉換爲Double類型的字符串
                   if(temp.indexOf(".")>-1){
                     singleRow[n] = String.valueOf(new Double(temp)).trim();
                   }else{
                     singleRow[n] = temp.trim();
                   }
                 }
                 break;
               case Cell.CELL_TYPE_STRING:
                 singleRow[n] = cell.getStringCellValue().trim();
                 break;
               case Cell.CELL_TYPE_ERROR:
                 singleRow[n] = "";
                 break;  
               case Cell.CELL_TYPE_FORMULA:
                 cell.setCellType(Cell.CELL_TYPE_STRING);
                 singleRow[n] = cell.getStringCellValue();
                 if(singleRow[n]!=null){
                   singleRow[n] = singleRow[n].replaceAll("#N/A","").trim();
                 }
                 break;  
               default:
                 singleRow[n] = "";
                 break;
             }
             n++;
          } 
          if("".equals(singleRow[0])){continue;}//如果第一行爲空,跳過
          dataList.add(singleRow);
      }
    }
    return dataList;
  }  
  /**
   * 返回Excel最大行index值,實際行數要加1
   * @return
   */
  public int getRowNum(int sheetIndex){
    Sheet sheet = wb.getSheetAt(sheetIndex);
    return sheet.getLastRowNum();
  }
  
  /**
   * 返回數據的列數
   * @return 
   */
  public int getColumnNum(int sheetIndex){
    Sheet sheet = wb.getSheetAt(sheetIndex);
    Row row = sheet.getRow(0);
    if(row!=null&&row.getLastCellNum()>0){
       return row.getLastCellNum();
    }
    return 0;
  }
  
  /**
   * 獲取某一行數據
   * @param rowIndex 計數從0開始,rowIndex爲0代表header行
   * @return
   */
    public String[] getRowData(int sheetIndex,int rowIndex){
      String[] dataArray = null;
      if(rowIndex>this.getColumnNum(sheetIndex)){
        return dataArray;
      }else{
        dataArray = new String[this.getColumnNum(sheetIndex)];
        return this.dataList.get(rowIndex);
      }
      
    }
  
  /**
   * 獲取某一列數據
   * @param colIndex
   * @return
   */
  public String[] getColumnData(int sheetIndex,int colIndex){
    String[] dataArray = null;
    if(colIndex>this.getColumnNum(sheetIndex)){
      return dataArray;
    }else{   
      if(this.dataList!=null&&this.dataList.size()>0){
        dataArray = new String[this.getRowNum(sheetIndex)+1];
        int index = 0;
        for(String[] rowData:dataList){
          if(rowData!=null){
             dataArray[index] = rowData[colIndex];
             index++;
          }
        }
      }
    }
    return dataArray;
    
  }
 }


參考:http://blog.csdn.net/jack0511/article/details/6179593

 

2、

package poi;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 ReadExcel001 {
	public static void main(String[] args) {
		readXml("D:/test.xlsx");
		System.out.println("-------------");
		readXml("d:/test2.xls");
 	}
	public static void readXml(String fileName){
		boolean isE2007 = false;	//判斷是否是excel2007格式
		if(fileName.endsWith("xlsx"))
			isE2007 = true;
		try {
			InputStream input = new FileInputStream(fileName);	//建立輸入流
			Workbook wb  = null;
			//根據文件格式(2003或者2007)來初始化
			if(isE2007)
				wb = new XSSFWorkbook(input);
			else
				wb = new HSSFWorkbook(input);
			Sheet sheet = wb.getSheetAt(0);		//獲得第一個表單
			Iterator<Row> rows = sheet.rowIterator();	//獲得第一個表單的迭代器
			while (rows.hasNext()) {
				Row row = rows.next();	//獲得行數據
				System.out.println("Row #" + row.getRowNum());	//獲得行號從0開始
				Iterator<Cell> cells = row.cellIterator();	//獲得第一行的迭代器
				while (cells.hasNext()) {
					Cell cell = cells.next();
					System.out.println("Cell #" + cell.getColumnIndex());
					switch (cell.getCellType()) {	//根據cell中的類型來輸出數據
					case HSSFCell.CELL_TYPE_NUMERIC:
						System.out.println(cell.getNumericCellValue());
						break;
					case HSSFCell.CELL_TYPE_STRING:
						System.out.println(cell.getStringCellValue());
						break;
					case HSSFCell.CELL_TYPE_BOOLEAN:
						System.out.println(cell.getBooleanCellValue());
						break;
					case HSSFCell.CELL_TYPE_FORMULA:
						System.out.println(cell.getCellFormula());
						break;
					default:
						System.out.println("unsuported sell type");
					break;
					}
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}


參考:http://blog.csdn.net/shuwei003/article/details/67416493

 

3、

代碼如下


public class Test {
 
 public static void main(String args[]){
  try {
   String  excelFilePath = "F://會員導入模板.xls";
           //模板.xlsx
 
   Workbook wb = null;
        int version=(excelFilePath.endsWith(".xls")?2003:2007);
        if(version==2003){
            try {
                InputStream stream=new FileInputStream(new File(excelFilePath));
                wb=new HSSFWorkbook(stream);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }else if(version==2007){
            try {
             InputStream stream=new FileInputStream(new File(excelFilePath));
                wb=new XSSFWorkbook(stream);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        
   String bs =""; 
        Sheet  sheet = wb.getSheetAt(0);
   Row row = null;
   int i=0;
   for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
    row = rit.next();
    i++;
    if(i>2){
     int j=0;
     bs+="(";
     for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) {
      Cell cell = cit.next();
      if(j>0){
       System.out.println(cell.getStringCellValue());
      }
      j++;
     }
     bs+=")";
    }
    
   }


   System.out.println(bs);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
}


參考:http://tiantianshagn.blog.163.com/blog/static/1676323272011101193551732/

4、

public class ReadExcel {

     /**
     * 對外提供讀取excel 的方法
     * */
public static List<List<Object>> readExcel(File file) throws IOException{
   String fileName = file.getName();
   String extension = fileName.lastIndexOf(".")==-1?"":fileName.substring(fileName.lastIndexOf(".")+1);
   if("xls".equals(extension)){
    return read2003Excel(file);
   }else if("xlsx".equals(extension)){
    return read2007Excel(file);
   }else{
    throw new IOException("不支持的文件類型");
   }
}


/**
* 讀取 office 2003 excel
* @throws IOException 
* @throws FileNotFoundException */
private static List<List<Object>> read2003Excel(File file) throws IOException{
   List<List<Object>> list = new LinkedList<List<Object>>();
   HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
   HSSFSheet sheet = hwb.getSheetAt(0);
   Object value = null;
   HSSFRow row = null;
   HSSFCell cell = null;
  
   for(int i = sheet.getFirstRowNum();i<= sheet.getPhysicalNumberOfRows();i++){
    row = sheet.getRow(i);
    if (row == null) {
     continue;
    }
    List<Object> linked = new LinkedList<Object>();
    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
     cell = row.getCell(j);
     if (cell == null) {
      continue;
     }
     DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
     DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字
     switch (cell.getCellType()) {
     case XSSFCell.CELL_TYPE_STRING:
      System.out.println(i+"行"+j+" 列 is String type");
      value = cell.getStringCellValue();
      break;
     case XSSFCell.CELL_TYPE_NUMERIC:
      System.out.println(i+"行"+j+" 列 is Number type ; DateFormt:"+cell.getCellStyle().getDataFormatString());
      if("@".equals(cell.getCellStyle().getDataFormatString())){
         value = df.format(cell.getNumericCellValue());
      } else if("General".equals(cell.getCellStyle().getDataFormatString())){
         value = nf.format(cell.getNumericCellValue());
      }else{
        value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
      }
      break;
     case XSSFCell.CELL_TYPE_BOOLEAN:
      System.out.println(i+"行"+j+" 列 is Boolean type");
      value = cell.getBooleanCellValue();
      break;
     case XSSFCell.CELL_TYPE_BLANK:
      System.out.println(i+"行"+j+" 列 is Blank type");
      value = "";
      break;
     default:
      System.out.println(i+"行"+j+" 列 is default type");
      value = cell.toString();
     }
     if (value == null || "".equals(value)) {
      continue;
     }
     linked.add(value);
    
   }
    list.add(linked);
   }
  
   return list;
}



/**
* 讀取Office 2007 excel
* */

private static List<List<Object>> read2007Excel(File file) throws IOException {

   List<List<Object>> list = new LinkedList<List<Object>>();
   // 構造 XSSFWorkbook 對象,strPath 傳入文件路徑
   XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
   // 讀取第一章表格內容
   XSSFSheet sheet = xwb.getSheetAt(0);
   Object value = null;
   XSSFRow row = null;
   XSSFCell cell = null;
   for (int i = sheet.getFirstRowNum(); i <= sheet
     .getPhysicalNumberOfRows(); i++) {
    row = sheet.getRow(i);
    if (row == null) {
     continue;
    }
    List<Object> linked = new LinkedList<Object>();
    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
     cell = row.getCell(j);
     if (cell == null) {
      continue;
     }
     DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
     DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字

     switch (cell.getCellType()) {
     case XSSFCell.CELL_TYPE_STRING:
      System.out.println(i+"行"+j+" 列 is String type");
      value = cell.getStringCellValue();
      break;
     case XSSFCell.CELL_TYPE_NUMERIC:
      System.out.println(i+"行"+j+" 列 is Number type ; DateFormt:"+cell.getCellStyle().getDataFormatString());
      if("@".equals(cell.getCellStyle().getDataFormatString())){
        value = df.format(cell.getNumericCellValue());
      } else if("General".equals(cell.getCellStyle().getDataFormatString())){
        value = nf.format(cell.getNumericCellValue());
      }else{
       value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
      }
      break;
     case XSSFCell.CELL_TYPE_BOOLEAN:
      System.out.println(i+"行"+j+" 列 is Boolean type");
      value = cell.getBooleanCellValue();
      break;
     case XSSFCell.CELL_TYPE_BLANK:
      System.out.println(i+"行"+j+" 列 is Blank type");
      value = "";
      break;
     default:
      System.out.println(i+"行"+j+" 列 is default type");
      value = cell.toString();
     }
     if (value == null || "".equals(value)) {
      continue;
     }
     linked.add(value);
    }
    list.add(linked);
   }
   return list;
}

}

說明:該類中共封裝了三個方法,對外提供的讀取excel文件的方法,兩個私有的分別讀取excel2003和excel2007的方法。外部使用,只需調用readExcel 方法,傳入一個File 參數,程序根據文件擴展名來判斷選取那個方法來讀取Excel文件。
 


參考http://hi.baidu.com/%D2%BB%C6%F0%D7%DF%BA%F3/blog/item/81d938d06f16f281a1ec9c47.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章