Print the Empty cell Adjacent cell value in Excel Sheet using Java - java

I have an Excel sheet I need to print the adjacent cell value when I am seeing the empty cell in java.
I had written the code to print the values in the Excel sheet and I too find the empty cell but I don't how to print the adjacent cell value on seeing the empty cell
public class empty {
public static void main(String args[]) throws Exception {
InputStream ExcelFileToRead = new FileInputStream("C:\\Users\\GOMATHI\\Desktop\\data1.xls");
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();
if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
// logic goes here. I don't know.
System.out.println(no);
}
System.out.println(cell.toString());
}
}
// System.out.println();
}
}
Input: Excel File
Id Value
01 200
02 201
03 203
04
05 205
Output:
The Value at 4th cell Value is empty so I need to print its corresponding ID.
04

First, I think your test if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) is half useless because cell should never be null.
Assuming this, you can get the cell of the previous column with row.getCell(cell.getColumnIndex() - 1)

Related

cellIterator.hasNext() returns false even the cell has value

I use the following approach to read data from excel (csv) sheet:
InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
XSSFWorkbook myWorkBook = new XSSFWorkbook(inputStream);
List<String> cellList = new ArrayList<>();
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
cellList.clear();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) { // this returns false even the cell has data
Cell cell = cellIterator.next();
cellList.add(cell.getStringCellValue());
}
}
I want to make cellIterator.hasNext() returns true for empty cell values as in the second row (name). So, how can I do that?
Create Date Uuid Name
2021-09-29 2e81a2b6-3226-4fe0-b8bd-39f42239686d admin
2021-09-30 610e9040-840c-48c5-aa64-f193ed896133
You can't make cellIterator.hasNext() return true for the empty "name" cell.
If you know in advance the number of column in advance, you can use a loop and row.getCell(index).
for (int i = 0; i < 3; i++) {
Cell cell = row.getCell(i);
cellList.add(cell == null ? "Empty":cell.toString());
}
If you don't, you have to scan first of your file to count the number of columns.

How do i search and print a specific cell from an excel sheet using Apache POI?

i am writing java code for a library sorting project, what i want it to do is to search for a string across all cells within a specific column and then print the ones that contain the given substring, i want to do it through columns because i have a column for each piece of info about the book (author, title, ISBN), so is there a way to do this? i have written the following code so far for this (without the import statements though) and all it does is print the whole row for the book that contains a substring, i only need it to print a specific cell from that row after it selects it
public class testf {
static List<Row> getRows(Sheet sheet, DataFormatter formatter, FormulaEvaluator evaluator, String searchValue) {
List<Row> result = new ArrayList<Row>();
String cellValue = "";
for (Row row : sheet) {
for (Cell cell : row) {
cellValue = formatter.formatCellValue(cell, evaluator);
if (cellValue.contains(searchValue)) {
result.add(row);
break;
}
}
}
return result;
}
public static void main(String[] args) throws IOException, InvalidFormatException {
try
{
FileInputStream file = new FileInputStream(new File("C:\\\\Users\\\\abdul\\\\Desktop\\\\University Files\\\\Object-Oriented Programming\\\\Project files\\\\Book class\\\\Books & DDC.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Scanner a = new Scanner(System.in);
List<Row> filteredRows = getRows(sheet, formatter, evaluator, "y");
for (Row row : filteredRows) {
for (Cell cell : row) {
System.out.print(formatter.formatCellValue(cell, evaluator));
System.out.print("\t \t");
}
System.out.println();
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
That's because the method getRows returns all the rows where there is a cell with the wanted criteria, but it doesn't tell you which cell exactly, so what you need to do is return the cells.
getRows -> getCells
and the code for that method will be :
static List<Cell> getCells(Sheet sheet, DataFormatter formatter, FormulaEvaluator evaluator, String searchValue) {
List<Cell> result = new ArrayList<>();
String cellValue = "";
for (Row row : sheet) {
for (Cell cell : row) {
cellValue = formatter.formatCellValue(cell, evaluator);
if (cellValue.contains(searchValue)) {
result.add(cell);
break;
}
}
}
return result;
}
and as far as printing goes, you just loop through the list of cells and you pritn them normally, and if you for whatever reason need the row for a particular cell, you just call cell.getRow()
List<Cell> filteredCells = getCells(sheet, formatter, evaluator, "whatever");
for (Cell cell : filteredCells) {
System.out.print(formatter.formatCellValue(cell, evaluator));
System.out.print("\t \t");
Row cellsRow = cell.getRow();// if you need the full row
}
by the way, I don't know about the specifications that you have, but the break that you have in your filtering method means that if a row has multiple cells with the wanted value, you'll only get the first cell, so be careful about that, i would recommend removing that break unless it's exactly what you want

Reading multiple columns for a row from excel, in java?

I want to read excel spreadsheet(.xlxs) having testcases preconditions column/expected result column and so on. How do i read multiple columns for specific row. Everyrow(first Column)is a testcase name.
I am able to read one row and two columns, but unsure how to read multiple columns for same row . I also don't want to hardcode column#,row# while reading it. Any suggestions?
Map<String,String> arrayExcelData = new Hashtable<String,String>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Cell methodNameCol = row.getCell(0);
Cell expectedResults = row.getCell(1);
if (expectedResults != null && methodNameCol !=null)
{
arrayExcelData.put(methodNameCol.getStringCellValue(),expectedResults.getStringCellValue());
}
workbook.close();
}
The Row class provides methods that return the index of the first and last cell (aka column) in that Row instance. Use these indexes to iterate over the columns:
Row row = rowIterator.next();
short firstCellNumber = row.getFirstCellNum();
short lastCellNumber = row.getLastCellNum();
for(short cellNumber = firstCellNumber; cellNumber < lastCellNumber; cellNumber++) {
Cell dataCell = row.getCell(cellNumber);
//Do something with the dataCell here
}

Append Excel columns with XSSFWorkbook

I have an excel sheet, and I want to selectively transfer its content to a list. The object has 2 attributes, String id, String str.
I want to set the first column as id. I got this part right. I also want to append the values of column 3,4,6,7. For example, if my excel looks like:
4404A01459C1 || A1 || 13 || 14 || B1 || 8 || 7
I want 4404A01459C1 as id(again, I got this part). Then I want 13;14;8;7, skipping A1 and B1, separating the values with ; How do I achieve this?
FileInputStream inputStream = new FileInputStream("D:\\work\\calculatepi\\test.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.iterator();
List<SampleGene> sgl=new ArrayList<SampleGene>();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
SampleGene sg = new SampleGene();
sg.setId(row.getCell(0).toString());
//need help here
sgl.add(sg);
}
return null;
Try using StringBuilder and iterate over cellIterator;append each cell value to the StringBuilder.
StringBuilder sb = new StringBuilder();
while(cellIterator.hasNext())
{
sb.append(cellIterator.next().toString());
sb.append(";");
}
sg.setStr(sb.toString());

How to check if excel file is blank?

I have excel file (*.xls or *.xlxs) which can have records or no records. First I store the file in some temp location, then copy the contents of the file and then tried to read the file. This scenario works fine if the excel sheet contains records but if the sheet has no record and the file is empty. This scenario does not work. I am using apache-poi to read the excel file contents.
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
return false;
}
}
return true;
}
I get IOException : unable to read entire header 0 bytes read expected 512 bytes. Can somebody suggest me a way to get rid of this exception and check the excel file is empty?
Googling and some experiments with org.apache.poi library suggest to me that it is abnormal to check if xls file is empty without knowing even approximately the data structure within it. It's as hard as to say if, for example, Oracle BD is empty.
Any way, you are able to fetch quantity of sheets then iterate over all of them, check rows and cells and consider file is empty if you found nothing.
HSSFWorkbook wBook = new HSSFWorkbook(new FileInputStream("your_path"));
for(int i = 0; i < wBook.getNumberOfSheets(); i++){
System.out.println("Sheet " + i + " has data: " + isSheetEmpty(wBook.getSheetAt(i)));
}
boolean isSheetEmpty(HSSFSheet sheet){
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
if(!cell.getStringCellValue().isEmpty()){
return true;
}
}
}
return false;
}
Using Apache Poi (org.apache.poi) for the solution and skipping the parts where I actually get the Workbook (excel) and get access to it's sheets.
If you want to know if sheet is empty use this, modify the solution to loop through sheets to find out if all of the sheets in the file are empty.
if (sheet.getLastRowNum() == 0 && sheet.getRow(0) == null) {
// This is the case when the sheet is empty!
}
getLastRowNum() - returns 0 in case of empty sheet or if there is only data in the first row
getRow(0) - returns null if there is no data in the row
NOTE: the solution doesn't take empty strings, spaces, empty lines and etc. into account
Below code worked for me.
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
XSSFSheet sheet = wb.getSheetAt(0);
private boolean isSheetEmpty(XSSFSheet sheet) {
Iterator rows = sheet.rowIterator();
Row row = null;
Cell cell = null;
while (rows.hasNext()) {
row = (Row) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (Cell) cells.next();
if (!cell.getStringCellValue().isEmpty()) {
return true;
}
}
}
return false;
}
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return true;
}
return false;
Try this one !

Categories