package com.softvan.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PoiExcel {
/**
* @param fileName
* @throws IOException
* @author dinglinhao
*/
public static void read_EXCEL(String fileName) throws IOException{
InputStream input =new FileInputStream(fileName);
XSSFWorkbook wb =new XSSFWorkbook(input);
//得到EXCEL中sheet的个数
int totalSheets=wb.getNumberOfSheets();
//System.out.println("Sheet的个数:"+totalSheets);
//循环遍历得到每一个sheet
for(int i=0;i<totalSheets;i++){
XSSFSheet sheet =wb.getSheetAt(i);
//获得sheet中的行数
int totalRows =sheet.getLastRowNum();
//循环遍历得到sheet中的每一行ROW
for(int a=0;a<totalRows;a++){
XSSFRow row=sheet.getRow(a);
//得到每一行中的单元格数
int totalCells =row.getLastCellNum();
//遍历单元格,根据单元格中的内容的类型不同取得各单元格中内容
for(int b=1;b<totalCells;b++){
XSSFCell cell=row.getCell(b);
//初始化类型ID(typeID)的值为0
int typeID=0;
try{
typeID=cell.getCellType();
}catch(NullPointerException e){
//异常处理
typeID=99;
}
//根据类型ID调用不同的方法获得单元格中的内容
switch(typeID){
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue()+"\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+"\t\t");
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(cell.getCellFormula()+"\t\t");
break;
case Cell.CELL_TYPE_ERROR:
System.out.print(cell.getErrorCellString()+"\t\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue()+"\t\t");
break;
case Cell.CELL_TYPE_BLANK:
System.out.print("BLANK");
break;
default:
System.out.print("\t\t");
break;
}
}
System.out.println();
}
System.out.println();
}
//关闭
input.close();
}
}
测试类
package com.softvan.dao;
import java.io.IOException;
public class Test {
/**
* @param args
* @throws IOException
* @author dinglinhao
*/
public static void main(String[] args) throws IOException {
//fileName变量EXCEK接收文件地址
String fileName ="D://Book1.xlsx";
//调用PoiExcel类的静态方法read_EXCEL
PoiExcel.read_EXCEL(fileName);
}
}