Java使用poi包读取execl

  Execl分为两个版本,后缀名分别为.xls和.xlsx,读取两种不同版本的execl使用不同的类,所需包直接从apache官网下载导入即可

一、读取.xls类型的execl文件

/**

*读取后缀名为.xls的execl文件

*

*@param filePath

*@return

*@throws Exception

*/

public static boolean readXls(String filePath){

InputStream is=null;

HSSFWorkbook hssfWorkbook=null;

try {

is = new FileInputStream(filePath);

hssfWorkbook = new HSSFWorkbook(is);

// 读取第一张execl表

HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);

int rowNum = 0;

DecimalFormat df = new DecimalFormat("#");

boolean hasMessyCode=false;

for (rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {

HSSFRow row = hssfSheet.getRow(rowNum);

int cellNumber=row.getLastCellNum();

for(int cellNum=0;cellNum<=cellNumber;cellNum++){

HSSFCell cell=row.getCell(cellNum);

switch (cell.getCellType()) {

case XSSFCell.CELL_TYPE_STRING:     //字符串类型

String cell=row.getCell(cellNum).getStringCellValue();   //进行逻辑处理

break;

case XSSFCell.CELL_TYPE_NUMERIC:   //数值类型

String cell=df.format(cell.getNumericCellValue()).toString();

break;

case XSSFCell.CELL_TYPE_BOOLEAN:   //布尔类型

String cellValue=String.valueOf(cell.getBooleanCellValue());

break;

case XSSFCell.CELL_TYPE_FORMULA:  //表达式类型

String cell=cell.getCellFormula()+"";

break;

default:

break;

}

}

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

canOpen=0;

}

return false;

}

二、读取.xlsx类型的execl文件

/**

*读取后缀名为。xlsx的execl文件

*

*@param filePath

*@return

*@throws Exception

*/

public static boolean readXlsx(String filePath){

InputStream is=null;

XSSFWorkbook xssfWorkbook=null;

try {

is = new FileInputStream(filePath);

xssfWorkbook = new XSSFWorkbook(is);

// 读取第一个execl表

XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

int rowNum = 0;

DecimalFormat df = new DecimalFormat("#");

boolean hasMessyCode=false;

for (rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {

XSSFRow row = xssfSheet.getRow(rowNum);

int cellNumber=row.getLastCellNum();

for(int cellNum=0;cellNum<=cellNumber;cellNum++){

//校验cell值

XSSFCell cell=row.getCell(cellNum);

switch (cell.getCellType()) {

case XSSFCell.CELL_TYPE_STRING:

String cellStr=row.getCell(cellNum).getStringCellValue();

break;

case XSSFCell.CELL_TYPE_NUMERIC:

String cellStr=df.format(cell.getNumericCellValue()).toString();

break;

case XSSFCell.CELL_TYPE_BOOLEAN:

String cellStr=String.valueOf(cell.getBooleanCellValue());

break;

case XSSFCell.CELL_TYPE_FORMULA:

String cellStr=cell.getCellFormula()+"";

break;

default:

break;

}

}

}

} catch (Exception e) {

// TODO Auto-generated catch block

canOpen=0;

e.printStackTrace();

}

return false;

}

你可能感兴趣的:(Java使用poi包读取execl)