使用 Apache POI讀取EXCEL文件


添加MAVEN依賴

<dependency>
    <groupid>org.apache.poi</groupid>
    <artifactid>poi</artifactid>
    <version>3.12</version>
</dependency>


讀取EXCEL文件

比如:
test.xls
java read excel file


try {
             
            FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
             
            //Get the workbook instance for XLS file 
            HSSFWorkbook workbook = new HSSFWorkbook(file);
 
            //Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);
             
            //Iterate through each rows from first sheet
            Iterator<row> rowIterator = sheet.iterator();
            while(rowIterator.hasNext()) {
                Row row = rowIterator.next();
                 
                //For each row, iterate through each columns
                Iterator<cell> cellIterator = row.cellIterator();
                while(cellIterator.hasNext()) {
                     
                    Cell cell = cellIterator.next();
                     
                    switch(cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t\t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "\t\t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
            FileOutputStream out = 
                new FileOutputStream(new File("C:\\test.xls"));
            workbook.write(out);
            out.close();
             
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
</cell></row>

輸出:
Emp Id      Name        Salary     
1.0     John        2000000.0      
2.0     Dean        420000.0       
3.0     Sam     280000.0       
4.0     Cass        6000000.0  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章