POI读取excel

读取excel的底层封装代码
/**
 * Copyright : HP
 * project : CIS Tools
 * Create by : Steven Zhang(Ling Kai)
 * Create on : 2011-7-25
 */
package com.hp.ucmdb.cis.tools.parse;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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 abstract class ParseExcel {
	private Sheet sheet;
	private FileInputStream fis;
	private Row row;
	private Cell cell;
	
	protected void init(String fileName, int sheetIndex) {
		String path = System.getProperty("user.dir") + "/file/" + fileName;
		System.out.println("path=" + path);

		try {
			fis = new FileInputStream(path);
			Workbook workBook = new XSSFWorkbook(fis);
			sheet = workBook.getSheetAt(sheetIndex);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	protected String getValue(int rowIndex, int column) {
		row = sheet.getRow(rowIndex);
		if(row == null){
			return null;
		}
		cell = row.getCell(column);
		if(cell == null){
			return null;
		}
		if(cell.getCellType() == Cell.CELL_TYPE_STRING){
			return cell.getStringCellValue().trim();
		}
		else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
			return String.valueOf(cell.getBooleanCellValue());
		}else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
			return String.valueOf((int)(cell.getNumericCellValue()));
		}else{
			return null;
		}
	}
	
	protected int getSheetRowLength(){
		System.out.println("sheet.getLastRowNum()="+sheet.getLastRowNum());
		return sheet.getLastRowNum();
	}
	
	protected void free(){
		try {
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

你可能感兴趣的:(Excel)