I am trying to read excel in java.I have following code.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.
add xmlbeans-2.3.0.jar
file to your classpath.
Add
xmlbeans-2.3.0.jar
dom4j-1.6.1.jar
along with regular POI XMLs, it will surely solve the issue.
Use this : Input String filePath Output is list of list of json objects
Have these dependencies
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
/**
* Function reads the input excel and gives list(sheet) of objects(rows of each sheet)
* @param filePath
* @return list of list of json objects
*/
public static List<List> excelFileReader(String filePath){
List<List>totalSheetList=new ArrayList<>();
XSSFWorkbook workbook= null;
try {
workbook = new XSSFWorkbook(filePath);
} catch (IOException e) {
e.printStackTrace();
}
//iteration for sheets in a workbook
for(int sheetIndex=0;sheetIndex<workbook.getNumberOfSheets();sheetIndex++){
XSSFSheet sheet=workbook.getSheetAt(sheetIndex);
XSSFRow row=null;
List<JSONObject> singleSheetList=new ArrayList<>();
//excel header - first row and non-empty
String[] header=new String[sheet.getRow(0).getPhysicalNumberOfCells()];
if (sheet.getPhysicalNumberOfRows()!=0 && sheet.getRow(0).getRowNum()==0) {
row=sheet.getRow(0);
for(int index=0;index<row.getPhysicalNumberOfCells();index++){
header[index]=(row.getCell(index).getStringCellValue());
}
}
//if header exists , start reading the values excluding first row (header)
if(header.length!=0){
for(int rowIndex=1;rowIndex<sheet.getPhysicalNumberOfRows();rowIndex++){
row=sheet.getRow(rowIndex);
HashMap<String,Object> eachRow=new HashMap<>();
for(int colIndex=0;colIndex<header.length;colIndex++) {
String cell = "";
if(row.getCell(colIndex)==null){
cell="";
}else{
if(row.getCell(colIndex).getCellType()==Cell.CELL_TYPE_STRING){
cell = row.getCell(colIndex).getRichStringCellValue().toString();
}else{
row.getCell(colIndex).setCellType(Cell.CELL_TYPE_STRING);
cell=row.getCell(colIndex).getStringCellValue();
}
}
eachRow.put(header[colIndex], cell);
}
JSONObject eachRowJsonObject = new JSONObject(eachRow);
singleSheetList.add(eachRowJsonObject);
}
}
totalSheetList.add(singleSheetList);
}
return totalSheetList;
}
Add following jars and add them to your classpath then run your project.
Add following jar files: