简体   繁体   中英

Apache POI XSSF reading in excel files

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 = new FileInputStream(filename);   // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs);           // (2)
XSSFSheet sheet = wb.getSheetAt(0);               // (3)

...with all the relevant things imported. My problem is that when I hit run, it gets stuck at line (2), in almost an infinite loop. filename is just a string.

If anybody could give me some sample code on how to fix this I would really appreciate it. All i want right now is to read in a single cell from an xlsx file; I was using HSSF for xls files and had no problems.

Thanks for your help, Andrew

InputStream inp = null;
        try {
            inp = new FileInputStream("E:/sample_poi.xls");

            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Header header = sheet.getHeader();

            int rowsCount = sheet.getLastRowNum();
            System.out.println("Total Number of Rows: " + (rowsCount + 1));
            for (int i = 0; i <= rowsCount; i++) {
                Row row = sheet.getRow(i);
                int colCounts = row.getLastCellNum();
                System.out.println("Total Number of Cols: " + colCounts);
                for (int j = 0; j < colCounts; j++) {
                    Cell cell = row.getCell(j);
                    System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
                }
            }

        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inp.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

I bealive that this will answer your questions: http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook

In short, your code should look like this:

InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);

Why are you breaking the file into an InputStream? XSSFWorkbook has a constructor that simply takes the path as a String. Just hard code the path of the string in. Once you create the workbook you can create XSSFSheets from that. Then XSSFCells, which will then finally allow you to read the contents of a single cell (cells are based on x,y locations, essentially)

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("");
    }
}

this works fine: try it

File filename = new File("E:/Test.xlsx");
FileInputStream isr= new FileInputStream(filename);

Workbook book1 = new XSSFWorkbook(isr);
Sheet sheet = book1.getSheetAt(0);  
Iterator<Row> rowItr = sheet.rowIterator();
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");
  }
}

I have the same error, I have just updated the pom dependencies with the same version. It worked.

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>
// Load sheet- Here we are loading first sheet only
XSSFSheet xlSheet = wb.getSheetAt(0);

Here code recognizing only first sheet - In my Excel multiple sheets are there so facing problem to change sheet2 to sheet1(getSheetAt(0)) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM