1、在使用過程中,一直報錯 throw new ClassNotFoundException(name);原因:沒有導入xmlbeans-2.6.0.jar包,建議在使用poi時,將所有包都導入進工程。
2、案例源碼
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFCell; 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; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test; public class TestExcelS { public static String filePath = TestExcel.class.getResource("/test.xlsx").getPath(); @Test public static void main(String[] args) { readXml(filePath); System.out.println("-------------"); } public static void readXml(String fileName){ boolean isE2007 = false; //判斷是否是excel2007格式 if(fileName.endsWith("xlsx")) isE2007 = true; try { InputStream input = new FileInputStream(fileName); //建立輸入流 Workbook wb = null; //根據文件格式(2003或者2007)來初始化 if(isE2007) wb = new XSSFWorkbook(input); else wb = new HSSFWorkbook(input); Sheet sheet = wb.getSheetAt(0); //獲得第一個表單 Iterator<Row> rows = sheet.rowIterator(); //獲得第一個表單的迭代器 while (rows.hasNext()) { Row row = rows.next(); //獲得行數據 System.out.println("Row #" + row.getRowNum()); //獲得行號從0開始 Iterator<Cell> cells = row.cellIterator(); //獲得第一行的迭代器 while (cells.hasNext()) { Cell cell = cells.next(); System.out.println("Cell #" + cell.getColumnIndex()); switch (cell.getCellType()) { //根據cell中的類型來輸出數據 case HSSFCell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println("unsuported sell type"); break; } } } } catch (IOException ex) { ex.printStackTrace(); } } }
相關代碼注釋可參考Java使用poi讀取Excel2003