poi方式读取Excel文件
1 package poi; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Date; 6 7 import org.apache.commons.io.FileUtils; 8 import org.apache.poi.hssf.usermodel.HSSFCell; 9 import org.apache.poi.hssf.usermodel.HSSFDateUtil; 10 import org.apache.poi.hssf.usermodel.HSSFRow; 11 import org.apache.poi.hssf.usermodel.HSSFSheet; 12 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 13 14 public class PoiReadExcel { 15 16 public static void main(String[] args) { 17 18 File file = new File("e:/poi_exp.xls"); 19 20 try { 21 HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file)); 22 HSSFSheet sheet = workbook.getSheet("Sheet0");//getSheetAt(index); 23 int firstRowNum = 0; 24 //获取最后一行行号 25 int lastRowNum =sheet.getLastRowNum(); 26 for (int i = firstRowNum; i < lastRowNum; i++) { 27 HSSFRow row = sheet.getRow(i); 28 //获取当前行的最后一个单元格列号 29 int lastCellNum = row.getLastCellNum(); 30 for (int j = 0; j < lastCellNum; j++){ 31 HSSFCell cell = row.getCell(j); 32 if(cell != null){ 33 //获取数据类型 34 switch (cell.getCellType()) { 35 //整型 36 case HSSFCell.CELL_TYPE_NUMERIC: 37 if(HSSFDateUtil.isCellDateFormatted(cell)){ 38 Date date = cell.getDateCellValue(); 39 System.out.println(date.toString()); 40 }else{ 41 int val = (int)cell.getNumericCellValue(); 42 System.out.print(val + " "); 43 break; 44 } 45 //字符串 46 case HSSFCell.CELL_TYPE_STRING: 47 String val1 = cell.getStringCellValue(); 48 System.out.print(val1 + " "); 49 break; 50 51 default: 52 System.out.println("what's heppend?"); 53 break; 54 } 55 } 56 } 57 System.out.println(); 58 } 59 workbook.close(); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 64 } 65 66 }