? Execl分為兩個版本,后綴名分別為.xls和.xlsx甸怕,讀取兩種不同版本的execl使用不同的類博敬,所需包直接從apache官網(wǎng)下載導(dǎo)入即可
一、讀取.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:???//數(shù)值類型
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;
}