用到了Apache的→POI插件←,可點擊鏈接從官網下載,目前已更新至4.0版本
1.將下載好的放入lib(class_path)目錄下,
2.編寫代碼
package com.fyf.test; import java.io.FileInputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class PoiRead { public static void main(String[] args) { // TODO Auto-generated method stub try { FileInputStream fStream = new FileInputStream("D:/test.xls"); Workbook wb = new HSSFWorkbook(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 static String getStringCell(Cell cell) { String result = ""; int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: result = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC:
//這里將數組作為日期返回 result = String.valueOf(cell.getDateCellValue()); break; case Cell.CELL_TYPE_STRING: result = cell.getStringCellValue(); break; default: break; } return result; } }