Searching Specific Excel Cell using Java Apache POI - java

I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file

using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}

Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}

Related

How to Get Cell value from Excel sheet in Java according to particular Column name and Row name

I want to get cell value according to the particular column name and row name.
This is the code that I have written to achieve it. It's working fine for the first sheet in the workbook but giving me Null pointer exception for the other sheet in the same workbook.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public FileInputStream fis;
String path = null;
private XSSFWorkbook workbook=null;
private XSSFSheet sheet;
private XSSFRow row=null;
private XSSFCell cell=null;
public ExcelReader() throws IOException {
path = System.getProperty("user.dir") + "\\Testdata.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
}
public String getCellData(String sheetName, String testDataType, String testDataID) throws IOException {
sheet = workbook.getSheet(sheetName);
int i;
for(i=0;i<=sheet.getRow(0).getLastCellNum(); i++) {
row = sheet.getRow(0);
cell = row.getCell(i);
if(cell.getStringCellValue().equalsIgnoreCase(testDataType)) {
break;
}
}
for(int j=0; j<=sheet.getLastRowNum();j++) {
row = sheet.getRow(j);
cell= row.getCell(0);
DataFormatter df2 = new DataFormatter();
String valueAsString = df2.formatCellValue(cell);
if(testDataID.equals(valueAsString)) {
break;
}
}
cell=row.getCell(i);
String S= cell.getStringCellValue();
fis.close();
return S;
}
}

Reading Test Data from Excel Sheet by using Selenium WebDriver with java

I am able to read data from excel sheet. However, when I am trying to enter data value from excel sheet into web application it is throwing error message GetCell is not allowing in the eclipse.
please use below code, it will work.
Java Class:
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;
import org.testng.annotations.Test;
public class TestAutomation {
#Test(groups = { "test_proxy" })
public void test_proxy() throws Exception {
try {
FileInputStream file = new FileInputStream(
new File("d:\\test.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);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

unable to replace the date in the excel file using java

Requirement
i need to open excel file. Then i need to check for the date(12/31/2014). If this exist in the file then i need replace with 11/28/2014. Actually excel file is containing the date. But in my code is never passing this condition if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {.
Here is the code:
package excelAsOfDate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelAsOfDate {
public static void main(String[] args) {
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Date newAsOfDate = df.parse("11/28/2014");
System.out.println("date as of" + df.format(asOfDate));
File directory = new File("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".xlsx")) {
FileInputStream fis = new FileInputStream(file.getAbsoluteFile());
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(fis);
int i = 1;
while (i < workbook.getNumberOfSheets()) {
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(i);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {
// System.out.println(df.format(cell.getDateCellValue()));
System.out.println(df.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy"));
cell.setCellValue(newAsOfDate);
cell.setCellStyle(cellStyle);
}
}
break;
}
}
}
i++;
fis.close();
}
//FileOutputStream fileOut = new FileOutputStream("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test//final//"+file.getName());
FileOutputStream fileOut = new FileOutputStream(file.getAbsoluteFile());
workbook.write(fileOut);
fileOut.close();
fis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Logging is a key to find your answers.
As I look into the Cell class, I see there is a method named :
getDateCellCalue()
When we look at the setter of that :
void setCellValue(java.util.Date value)
Converts the supplied date to its equivalent Excel numeric value and sets that into the cell.
So you are not comparing correct.
Mine quick suggestion is :
if (df.format(cell.getDateCellValue()).equals(df.format(asOfDate)))
If this doesn't work, put logging on what the df.format(cell.getDateCellValue() produces as String.
Edit :
Did you also noticed this :
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Your second date is MM/dd/yyyy

The PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object

I've created this code and The PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object. The 'POI Worksheet' will then be read into an HSSFWorksheet object, and then the values within the A1, B1, C1, and D1 cells will be read and displayed to standard output.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
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;
public class PoiReadExcelFile {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("poi-
test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("POI Worksheet");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
HSSFCell cellC1 = row1.getCell((short) 2);
boolean c1Val = cellC1.getBooleanCellValue();
HSSFCell cellD1 = row1.getCell((short) 3);
Date d1Val = cellD1.getDateCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
System.out.println("C1: " + c1Val);
System.out.println("D1: " + d1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When i ran this code i got this:
Usage: BiffDrawingToXml [options] inputWorkbook
Options:
-exclude-workbook exclude workbook-level records
-sheet-indexes output sheets with specified indexes
-sheet-namek output sheets with specified name
What's the problem?
Please run the class file using right click run option. The above message while come when the only JAR file is getting run.

Overwriting an excel file using Java POI

I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}

Categories