java實現簡單的poi匯入excel
阿新 • • 發佈:2018-12-10
示例程式碼
public void poiTest(){ File file = new File("xxx\\test.xlsx") ; InputStream input = new FileInputStream(file) ; String fileName = file.getName() ; /* web接收的MultipartFile類 MultipartFile file; InputStream input = file.getInputStream(); String fileName = file.getOriginalFilename() ; */ Workbook wb = fileName.endsWith("xlsx") ? new XSSFWorkbook(input) : new HSSFWorkbook(input); // 獲得第一個表單 Sheet form = wb.getSheetAt(0); int rows = form.getLastRowNum(); // 第二行開始讀取,第一行為title文案 for (int i = 1; i <= rows; i++) { int column = 0 ; Row row = form.getRow(i) ; // 空行,結束 if(row == null) break ; // 第一列 Cell cell1 = row.getCell(column++); // 設定為字串型別 if (cell1 != null){ cell1.setCellType(cell1.CELL_TYPE_STRING); System.out.println("第"+(i+1)+"行,"+ "第"+column+"列資料:"+cell1.getStringCellValue()); } // 第二列 Cell cell2 = row.getCell(column++); // 設定為字串型別 if (cell2 != null){ cell2.setCellType(cell2.CELL_TYPE_STRING); System.out.println("第"+(i+1)+"行,"+ "第"+column+"列資料:"+cell2.getStringCellValue()); } } }
maven
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.9</version>
</dependency>