Apache POI XSSF reading in excel files

前端 未结 8 2072
北恋
北恋 2021-02-13 00:00

I just have a quick question about how to read in an xlsx file using the XSSF format from Apache.

Right now my code looks like this:

InputStream fs = ne         


        
相关标签:
8条回答
  • 2021-02-13 00:38
    public class ExcelReader{
       public String path;
       public static FileInputStream fis;
    
       public ExcelReader(){
          System.out.println("hello");
       }
    
       public ExcelReader(String path){
          this.path=path;
          fis=new FileInputStream(path);
          XSSFWorkbook workbook=new XSSFWorkbook(fis);
          XSSFSheet sheet=workbook.getSheet("Sheet1");//name of the sheet
          System.out.println(sheet.getSheetName());
          System.out.println(sheet.getLastRowNum());
          System.out.println(sheet.getRow(2).getCell(3));
      }
      public static void main(String[] args) throws IOException {
          ExcelReader excel=new ExcelReader("path of xlsx");
      }
    }
    
    0 讨论(0)
  • 2021-02-13 00:50

    You can try the following.

    private static void readXLSX(String path) throws IOException {
        File myFile = new File(path);
        FileInputStream fis = new FileInputStream(myFile);
    
        // Finds the workbook instance for XLSX file
        XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
    
        // Return first sheet from the XLSX workbook
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
    
        // Get iterator to all the rows in current sheet
        Iterator<Row> rowIterator = mySheet.iterator();
    
        // Traversing over each row of XLSX file
        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_STRING:
                    System.out.print(cell.getStringCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t");
                    break;
                default :
    
                }
            }
            System.out.println("");
        }
    }
    
    0 讨论(0)
提交回复
热议问题