Java- How to read an xlsx file

Here is a sample code to read xlsx file from java

import java.io.File;
import java.io.FileInputStream;
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;

public class UploadSchools {

public static void main(String s[])
{
UploadSchools u=new UploadSchools();
u.readExcel(“/home/kamalmeet/schools.xlsx”);
}

public void readExcel(String path)
{
try{

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
Row currentRow = rows.next();

Iterator cells = currentRow.cellIterator();
while (cells.hasNext()) {

Cell currentCell = cells.next();
System.out.print(currentCell.toString()+”\t”);
}
System.out.println(“”);
}
workBook.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Note that I am simply printing string value of the cells. You can check the cell type and read the value accordingly. For example, add following utility method

private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + “”;
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + “”;
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + “”;
}
else {
return null;
}
}

References :

http://stackoverflow.com/questions/12526310/returning-decimal-instead-of-string-poi-jar

http://java67.blogspot.in/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html