Last active
October 30, 2023 21:13
-
-
Save madan712/5611191 to your computer and use it in GitHub Desktop.
Java - Read excel file with blank cells
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The new way looks like this for newer versions of Apache POI API
we need to set this attribute while creating object of XSSFWorkbook.