For Reading and writing the data from excelsheet. We have to provide the apache POI maven dependency in our maven project which will download the jars required for dealing with the excelSheet
Below is the Apache POI maven dependency
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
Please note we have to add two seperate maven dependencies so that we can read the data from xls and xlsx format excel sheet.
simple poi is for xls where as the second one poi-ooxml is for the xlsx.
How to read the data from xlsx excelSheet ?
Below is the program for reading the data from the excelSheet.
package org.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 ReadDataFromExcel {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream(new File("C:\\Users\\Ankush\\git\\trainingjanuary\\automation\\Book1.xlsx"));
Workbook wb= new XSSFWorkbook(fis);
Sheet sheet= wb.getSheetAt(0);
/** Sheet sheet= wb.getSheet("Sheet Name"); */
Row firstRow=sheet.getRow(0);
Cell firstCell=firstRow.getCell(0);
Cell secondCell=firstRow.getCell(1);
/** Cell thirdCell=firstRow.getCell(2); */ //java.lang.NullPointerException
System.out.println(firstCell.getStringCellValue());
System.out.println(secondCell.getStringCellValue());
/** System.out.println(thirdCell.getStringCellValue()); */
wb.close();
}
}
