java poi中的一个小实例

package com.attendance.commons;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;

public class ReadExcel{

private String _xlsPath = "";
private String _sheetName;
private String _cellString;
private int _sheetIndex;
private HSSFWorkbook _workbook;
private HSSFSheet _sheet;


public ReadExcel(){

}

public ReadExcel(String xlspath){

this._xlsPath = xlspath;
_workbook = this.getWorkbook(this._xlsPath);
}

/**
* 初始化workbook
* @param xlspath
* @return HSSFWorkbook类型
*/
private HSSFWorkbook getWorkbook(String xlspath){

try{

_workbook = new HSSFWorkbook(new FileInputStream(_xlsPath));

}catch(Exception e) {

System.out.println("已运行 getWorkbook() : " + e );
}

return _workbook;
}

/**
* 设置xml的路径
* @param xlsPath
*/
public void setXlsPath(String xlsPath){
this._xlsPath = xlsPath;
}

/**
* 改变工作表名
* @param sheetName
*/
public void setSheetName(String sheetName){

this._sheetName = sheetName;
}

/**
* 根据工作表名得到工作表(Sheet)
* @return HSSFSheet
*/
public HSSFSheet getWorkBookSheetByName(){

_sheet = _workbook.getSheet(_sheetName);

return _sheet;
}
/**
* 设置工作表索引
* @param sheetIndex
*/
public void setSheetIndex(int sheetIndex){
this._sheetIndex = sheetIndex;
}
/**
*根据工作表索引得到工作表
* @param sheetIndex 索引数字
* @return HSSFSheet
*/
public HSSFSheet getWorkBookSheetByIndex(){

_sheet = _workbook.getSheetAt(_sheetIndex);

return _sheet;
}

/**
* 得到单元格的字段String型
* @param rowIndex
* @param listIndex
* @return String
*/
public String getCellString(int rowIndex,int listIndex){

try{//捕获单元格是空值情况
HSSFRow row = _sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short)listIndex);
_cellString = cell.getStringCellValue(); //String
}catch(Exception e){
// System.out.print(e.getMessage());
if(e.getMessage()==null){
_cellString="";
}
}
return _cellString;
}

/**
* 得到单元格的字段以String型式返回Date
* @param rowIndex
* @param listIndex
* @return String
*/
public String getCellDate(int rowIndex,int listIndex){

HSSFRow row = _sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short)listIndex);
try{//捕获单元格是空值情况
_cellString = cell.getDateCellValue().toString(); //Date

}catch(Exception e){
// System.out.print(e.getMessage());
if(e.getMessage()==null){
_cellString="";
}
}
return _cellString;
}
/**
* 判断某单无格是否是日期型数据
* @param rowIndex
* @param listIndex
* @return 若不是日期型则抛出异常
*/
public void isDate(int rowIndex,int listIndex) throws Exception{
HSSFRow row = _sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short)listIndex);
cell.getDateCellValue();
}

/**
* 获取单元格的类型
* @param rowIndex
* @param listIndex
* @return 数字、日期、时间:0 字符串:1
*/
public int getCellType(int rowIndex,int listIndex){
int intCellType=0;
try{
HSSFRow row = _sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short)listIndex);
intCellType=cell.getCellType();
}catch (Exception e) {
}
return intCellType;
}

}

你可能感兴趣的:(java,apache,工作,xml)