使用POI作數據導入首先須要添加POI依賴java
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.9</version> </dependency>
測試用例apache
package poitest; 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; import java.io.FileInputStream; /** * @Author: mol * @Description: * @Date: create in 8:56 2018/3/15 */ public class POITest { private String fileName = "E:\\corner\\下載 (12).xls"; @Test public void testPOi()throws Exception{ //判斷文件是不是Excel表格 if(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")){ //判斷Excel版本 boolean is03Excel = fileName.endsWith(".xls"); FileInputStream fileInputStream = new FileInputStream(fileName); //根據不一樣的版本建立對應的工做簿 Workbook workbook = is03Excel?new HSSFWorkbook(fileInputStream):new XSSFWorkbook(fileInputStream); //根據下標獲取工做表 Sheet sheet = workbook.getSheetAt(0); //獲取工做表最後一行的索引 int lastRowNum = sheet.getLastRowNum(); System.out.println(lastRowNum); //循環取出每一行 for(int rowNum = 2;rowNum < sheet.getLastRowNum(); rowNum++){ //獲取當前索引行 Row row = sheet.getRow(rowNum); //獲取當前行中第一個單元格row.getCell(0)獲取這個單元格的內容row.getCell(0).getStringCellValue() System.out.println("單位:"+row.getCell(0).getStringCellValue()); //Cell.CELL_TYPE_STRING將單元格的內容設爲String類型 不然可能會報 Cannot get a text value from a numeric cell row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); System.out.println("已導入學生人數:"+row.getCell(1).getStringCellValue()); row.getCell(2).setCellType(Cell.CELL_TYPE_STRING); System.out.println("考試人數:"+row.getCell(2).getStringCellValue()); row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); System.out.println("學習人數:"+row.getCell(3).getStringCellValue()); row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); System.out.println("及格率:"+row.getCell(4).getStringCellValue()); } } } }