packagecom.fyf.test;importjava.io.FileInputStream;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;public classPoiRead {public static voidmain(String[] args) {//TODO Auto-generated method stub
try{
FileInputStream fStream= new FileInputStream("D:/test.xls");
Workbook wb= newHSSFWorkbook(fStream);
Sheet sheet= wb.getSheetAt(0);
//因为Sheet接口继承了 java.lang.Iterable接口所以,遍历表中的行可以一用foreach很方便for(Row row : sheet) {
//跳过空行if (row==null) {continue;
}
System.out.print("row:"+row.getRowNum()+"\t");
//同理行中的单元格也可以用foreach遍历for(Cell cell : row) {if (cell==null) {continue;
}
//对cell进行判断后输出
System.out.print("|"+getStringCell(cell)+"\t|");
}
System.out.println();
}
}catch(Exception e) {//TODO: handle exception
e.printStackTrace();
}
}public staticString getStringCell(Cell cell) {
String result= "";int cellType =cell.getCellType();switch(cellType) {caseCell.CELL_TYPE_BOOLEAN:
result=String.valueOf(cell.getBooleanCellValue());break;caseCell.CELL_TYPE_NUMERIC:
//这里将数组作为日期返回
result=String.valueOf(cell.getDateCellValue());break;caseCell.CELL_TYPE_STRING:
result=cell.getStringCellValue();break;default:break;
}returnresult;
}
}