Read the data from excel is very easy these are following steps to read the data from excel.
Here is the java class to read data from excel sheet.
Explanation:
1. Create a workbook instance.
2. Create the file input stream object to read the data from the file.
3. Create the sheet using the sheet object.
4. Increment row number and iterate over all cells in a row by using the iterator.
5. Finally, close the file.
Here is the java class to read data from excel sheet.
package com.Excel; 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.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * * @author Janardhan Randhi */ public class ReadExcel { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("Javasnippet.xlsx")); // Create Workbook instance XSSFWorkbook workbook = new XSSFWorkbook(file); // Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); // Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); // For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "t"); break; } } System.out.println(""); } file.close(); } catch (IOException e) { e.printStackTrace(); } } }
1. Create a workbook instance.
2. Create the file input stream object to read the data from the file.
3. Create the sheet using the sheet object.
4. Increment row number and iterate over all cells in a row by using the iterator.
5. Finally, close the file.