Skip to content

Instantly share code, notes, and snippets.

@madan712
Last active October 30, 2023 21:13
Show Gist options
  • Save madan712/5611191 to your computer and use it in GitHub Desktop.
Save madan712/5611191 to your computer and use it in GitHub Desktop.
Java - Read excel file with blank cells
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcelFile {
public static final String EXCEL_FILE = "C:/Test.xls";
public static void readXLSFile() {
try {
InputStream ExcelFileToRead = new FileInputStream(EXCEL_FILE);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (HSSFCell) cells.next();
System.out.print(cell.toString()+" ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void readXLSFileWithBlankCells() {
try {
InputStream ExcelFileToRead = new FileInputStream(EXCEL_FILE);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (HSSFRow) rows.next();
for(int i=0; i<row.getLastCellNum(); i++) {
cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
System.out.print(cell.toString()+" ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
readXLSFile();
readXLSFileWithBlankCells();
}
}
Copy link

ghost commented Apr 30, 2020

Thank you so much for this, it really helped my out!

@Hani2105
Copy link

Thank you for your great solution.

@sourabh09
Copy link

sourabh09 commented Jan 15, 2023

The new way looks like this for newer versions of Apache POI API

XSSFWorkbook wb = new XSSFWorkbook(fis);
wb.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK);

we need to set this attribute while creating object of XSSFWorkbook.

@AkhilaChandupatla
Copy link

@sourabh09 absolute solution .
thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment