Fetch data from Excel file in Java

Hello Everyone! Here we will learn about how to read an excel sheet or fetch data from excel file in Java. In order to read data from an excel sheet, we need to import the required packages and use iterator class to iterate through the whole sheet every row and every cell.

Using the Iterator class, we can read data from an Excel sheet!

In order to read a particular sheet, we need to import the “FileInputStream” package. And create an instance to this class and copy the file path and pass it as an argument. To read a cell, row, a sheet from the file we need to import all the required packages mentioned below.

Next using Workbook class, create an instance and pass the file object as an argument.

Now create an “Iterator” class for a row and using “hasnext()” and “next” methods, we can iterate through each and every row. Within the row iterator class, create a cell iterator instance and read each and every cell’s data. Using a switch case, we can know the type of the cell using the “getCellType()” method and then print the data.

 

 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
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;
public class Main {
     
    public static void main(String[] args) throws IOException {
        String filepath= "excelsheet.xlsx";
        FileInputStream f = new FileInputStream(new File(filepath));
         
        Workbook workbook = new XSSFWorkbook(f);
        Sheet sheet1 = workbook.getSheetAt(0);
        Iterator<Row> i = sheet1.iterator();
         
        while (i.hasNext()) {
            Row r = i.next();
            Iterator<Cell> cell = nextRow.cellIterator();
             
            while (cell.hasNext()) {
                Cell c = cellIterator.next();
                 
                switch (c.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(c.getStringCellValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(c.getNumericCellValue());
                        break;
                }
                System.out.print(" : ");
            }
            System.out.println();
        }
         
        workbook.close();
        f.close();
    }
 
}

Look at our code and I hope, you will understand how we write our program to Fetch data from our Excel file with Java.

Also, read:



 

Leave a Reply

Your email address will not be published. Required fields are marked *