How can i get my javacode output as json - java

I am reading xlsx file using Apache POI. I am able to fetch the result and xlsx entities count successfully. but I want to get my result in JSON, so that I can use this JSON data to make google graph or any graph API. I am new to java, how can I do that? Any help will be appreciated.
My code details are below.
package com.amiku.Excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader
{
public static void main(String[] args) throws IOException{
{
FileInputStream fis = new FileInputStream(new File("C:\\Users\\amiku\\eclipse-workspace\\Amiku\\cloudstreams-connectors-downloads.xlsx"));
//create workInstance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrive the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//that is for evalute the cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
Map<String, Integer> Details = new HashMap<String,Integer>();
int i=0;
List<String> l = new ArrayList<String>();
for (Row row : sheet)
{
for (Cell cell : row) {
l.add(cell.getStringCellValue());
/*HashMap map = new HashMap();
map.put(cell.getStringCellValue());*/
}
/*switch(formulaEvaluator.evaluateInCell(cell).getCellType())
{*/
/*//if cell has a numeric format
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
// if cell has a string format
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}*/
i++;
System.out.println();
}
for (int j = 0; j < l.size(); j++) {
if (j % 2 == 1) {
String var = l.get(j);
if (Details.containsKey(var)) {
Details.put(var, Details.get(var) + 1);
} else {
Details.put(var, 1);
}
}
}
Iterator it = Details.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
}
}
my result image of this code is here.

you can create a expandible object and add key value pair to this object ,once all of your javacode output is set into this object,
simply serialize this object to json using one of the speficied library.

Related

Printing out results in a map loading contents from a xlsx file using POI

so I need to print out the product id and image url from a excel file as I need to modify another file with the contents I retrieve, however for some reason the mappings is empty, but if I print the values out directly it shows them correctly.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Main {
static final Map<String, String> PRODUCT_CODES_BY_IMAGES = new HashMap<>();
public static void main(String[] args) throws IOException, InvalidFormatException {
File file = new File("./data/stock_met_imageurls.xlsx");
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell != null && cell.getCellTypeEnum().equals(CellType.STRING)) {
String image_url = null;
String product_id = null;
switch(cell.getColumnIndex()) {
case 0:
image_url = cell.getStringCellValue();
break;
case 2:
product_id = cell.getStringCellValue();
break;
}
if(image_url != null && product_id != null) {
PRODUCT_CODES_BY_IMAGES.put(product_id, image_url);
}
}
}
}
PRODUCT_CODES_BY_IMAGES.forEach((k, v) -> {
System.out.println("key = " + k);
System.out.println("val = " + v);
});
System.out.println("Size = " + PRODUCT_CODES_BY_IMAGES.size());
}
}
if I did under the cases
System.out.println("val = " + cell.getStringCellValue());
it prints it out correctly but for some reason the mappings is empty?
Any help would be greatly appreciated.
Because your map is declared as static final. Check out https://www.baeldung.com/java-final
Fixed, I added the elements in the mappings above the wrong bracket.

Apache Poi - Value in a cell having error in existing workbook is not recalculated

I have an existing Excel workbook in which two "output" cells (with range name "rate" and "premium") have formulas based on values in other "input" cells (i.e. range names "loamamount", "loanterm", "age" and "smoker").
If, in the Excel workbook, I make all the input cells empty then the formulae evaluate to "#N/A". However when I populate the correct values in the input cells through poi and use the command
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
The value in the two cells is not recalculated and remains "#N/A".
Can anyone help me understand what I am doing wrong? The code is as follows:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFName;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class GetDataFromExcel {
public static void main(String[] args) throws IOException {
getData();
}
public static void getData() throws IOException {
String s, cCellName, cString;
XSSFName namedCell;
AreaReference aref;
CellReference[] crefs;
XSSFRow r;
XSSFCell c;
XSSFSheet sheet = null;
File directory = new File("./");
s = directory.getAbsolutePath();
s = s.substring(0, s.length() - 2);
InputStream ExcelFileToRead = new FileInputStream(s + "/src/main/java/Excel/Test1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
// Search for the Range names and set the input values
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("loanamount", 2000000);
map.put("age", 25);
map.put("smoker", "Y");
map.put("loanterm", 23);
for (HashMap.Entry<String, Object> entry : map.entrySet()) {
cCellName = entry.getKey();
namedCell = wb.getName(cCellName);
// Retrieve the cell at the named range and test its contents
aref = new AreaReference(namedCell.getRefersToFormula(), null);
crefs = aref.getAllReferencedCells();
for (int i = 0; i < crefs.length; i++) {
sheet = wb.getSheet(crefs[i].getSheetName());
r = sheet.getRow(crefs[i].getRow());
c = r.getCell(crefs[i].getCol(), Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
// extract the cell contents based on cell type etc.
cString = entry.getValue().toString(); // Add missing cell check
if (c.getCellType() == CellType.STRING) {
c.setCellValue(cString);
} else if (c.getCellType() == CellType.NUMERIC) {
c.setCellValue(Double.parseDouble(cString));
} else if (c.getCellType() == CellType.BOOLEAN) {
c.setCellValue(cString);
} else {
}
}
}
sheet = wb.getSheetAt(0);
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
// wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
// Get all the output values requested
Iterator<String> i;
ArrayList<String> outputValues = new ArrayList<String>();
outputValues.add("rate");
outputValues.add("premium");
i = outputValues.iterator();
while (i.hasNext()) {
cCellName = i.next();
namedCell = wb.getName(cCellName);
// retrieve the cell at the named range and test its contents
aref = new AreaReference(namedCell.getRefersToFormula(), null);
crefs = aref.getAllReferencedCells();
for (int j = 0; j < crefs.length; j++) {
sheet = wb.getSheet(crefs[j].getSheetName());
r = sheet.getRow(crefs[j].getRow());
c = r.getCell(crefs[j].getCol(), Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);/////
// extract the cell contents based on cell type etc.
System.out.println(cCellName +" : "+c.getRawValue());
}
}
wb.close();
}
}
Your code part which should set values into cells does not set values into cells. So because there are no cell values set and the cells remain empty, the formulas will result in #N/A error.
This is because blank cells will not be of any cell type you are testing in your code. A blank cell is of CellType.BLANK and not CellType.STRING nor CellType.NUMERIC nor CellType.BOOLEAN. So none of your if... will be true and so no value will be set into the cells.
Rather than trying to set cell values dependent of cell types which cannot exist for blank cells, you should put cell values dependent on entry value type.
Example:
...
for (HashMap.Entry<String, Object> entry : map.entrySet()) {
cCellName = entry.getKey();
namedCell = wb.getName(cCellName);
// Retrieve the cell at the named range and test its contents
aref = new AreaReference(namedCell.getRefersToFormula(), null);
crefs = aref.getAllReferencedCells();
for (int i = 0; i < crefs.length; i++) {
sheet = wb.getSheet(crefs[i].getSheetName());
r = sheet.getRow(crefs[i].getRow());
c = r.getCell(crefs[i].getCol(), Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
// put cell values dependent on entry value type
Object o = entry.getValue();
if (o instanceof String) {
c.setCellValue((String)o);
} else if (o instanceof Number) {
c.setCellValue(((Number)o).doubleValue());
} else if (o instanceof Boolean) {
c.setCellValue((Boolean)o);
} else {
}
}
}
...

For-loop prints only the last value of Array through whole Excel file

I am struggling through this IBAN Checker JAVA project where I am supposed to take IBANs from an excel sheet -> validate them -> print valid/invalid results back into Excel. I have it almost all set up but now I got stuck on looping function that should put already validated IBANS back to the sheet. Here I am getting only last IBAN number of my IBAN Array which gets printed into all the rows, other IBANs are not showing.
However, when I use "System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid");" function all the ibans are validated correctly and printed into console one by one.
Is there please some way to get the results of above "System.out.printf" and iterate them through the cells in the Excel sheet? Or would you have some suggestion for modifications of the for-loop please? I think something in the loop is causing the issue because when I put "System.out.prinf" function inside of the loop, it starts validating only the last IBAN number which means something with the loop is not right.
Thank you very much for any help you can give!
IBANChecker03.java
package ibanchecker03;
import java.math.BigInteger;
import java.util.*;
//EXCEL
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
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.openxml4j.exceptions.InvalidFormatException;
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;
//EXCEL
public class IBANChecker03 {
private static final String DEFSTRS = ""
+ "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 "
+ "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 "
+ "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 LB28 LI21 "
+ "LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 "
+ "PS29 PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 "
+ "TN24 TR26 AE23 GB22 VG24 GR27 CR21";
private static final Map<String, Integer> DEFINITIONS = new HashMap<>();
static {
for (String definition : DEFSTRS.split(" "))
DEFINITIONS.put(definition.substring(0, 2), Integer.parseInt(definition.substring(2)));
}
public static void printValid(String iban) throws FileNotFoundException, IOException, InvalidFormatException {
File file = new File("G:\\AR\\INVprint (GD Thomas)\\EKG.xls");
FileInputStream ExcelFile = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFile);
HSSFSheet sheet = wb.getSheet("SheetF");
System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid");
try {
for (int rowNumber = 0; rowNumber < sheet.getLastRowNum(); rowNumber++) {
HSSFRow row1 = sheet.getRow(rowNumber);
HSSFCell cell = row1.createCell(1);
cell.setCellValue(iban + " is " + validateIBAN(iban));
//System.out.println(cell);
//for(int columnNumber = 1; columnNumber < row1.getLastCellNum();) {
// HSSFCell cell = row1.createCell(columnNumber);
// if(cell != null) {
//cell.setCellValue("Darkness");
//System.out.println(cell);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("G:\\AR\\INVprint (GD Thomas)\\EKG.xls");
wb.write(fileOut);
wb.close();
} catch (FileNotFoundException e) {
throw new FileNotFoundException("File not faaund");
}
}
public static void main(String[] args) throws IOException, FileNotFoundException {
String[] ibans = {"GB33BUKB20201555555555"};
for (String iban : ibans) {
try {
printValid(iban);
} catch (InvalidFormatException ex) {
Logger.getLogger(IBANChecker03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
static boolean validateIBAN(String iban) {
iban = iban.replaceAll("\\s", "").toUpperCase(Locale.ROOT);
int len = iban.length();
if (len < 4 || !iban.matches("[0-9A-Z]+") || DEFINITIONS.getOrDefault(iban.substring(0, 2), 0) != len)
return false;
iban = iban.substring(4) + iban.substring(0, 4);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++)
sb.append(Character.digit(iban.charAt(i), 36));
BigInteger bigInt = new BigInteger(sb.toString());
return bigInt.mod(BigInteger.valueOf(97)).intValue() == 1;
}
}
HomeOffice.java
package ibanchecker03;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 HomeOffice {
public static void main(String[] args) throws Exception {
File excelFile = new File("G:\\AR\\INVprint (GD Thomas)\\TEST2 IBAN.xlsx");
FileInputStream fis = new FileInputStream(excelFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
//Here we start iterating through raws and cells
Iterator<Row> rowIt = sheet.iterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getColumnIndex() == 7) { // Choose number of column
//System.out.println(cell.toString() + ","); // Print cells
String cellvalue = cell.toString();
IBANChecker03.printValid(cellvalue);
}
}
workbook.close();
fis.close();
}
}
}

How to get value from a specific cell from XLSX file using java Apache POI library

I am writing a Java program to read data from excel sheet (having XLSX extension) using Apache POI library. I am able to iterate through all the cells and get all the values. But I am unable to get a specific cell value, say E10.
Is there any way to do this?
Please see the code below that I used for iterating through the cells.
package application;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.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 ReadFromXLSX {
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:\\Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
}
}
System.out.println();
}
}
}
For example, to get E10 of the first worksheet:
wb.getSheetAt(0).getRow(9).getCell(4);
Note: subtract one because the indices are null-based.
You can also use this convenience method to map E to 4.
wb.getSheetAt(0).getRow(9).getCell(CellReference.convertColStringToIndex("E"));
To get a value from a specific cell in excel you can use the below code line.
wb.getSheetAt(0).getRow(1).getCell(1);
XSSFSheet has the method getRow(int rownum)
It returns the logical row ( 0-based). If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.
Once you get the row, you can call getCell(int cellnum) method of XSSFRow object. It returns the cell at the given (0 based) index.
Just version-up the getCell method
public XSSFCell getCell(String cellName){
Pattern r = Pattern.compile("^([A-Z]+)([0-9]+)$");
Matcher m = r.matcher(cellName);
XSSFWorkbook wb = new XSSFWorkbook();
if(m.matches()) {
String columnName = m.group(1);
int rowNumber = Integer.parseInt(m.group(2));
if(rowNumber > 0) {
return wb.getSheetAt(0).getRow(rowNumber-1).getCell(CellReference.convertColStringToIndex(columnName));
}
}
return null;
}
Now you can get the cell easily by this line
getCell("E10")
public class XmlFileRead {
public static void main(String[] args) throws IOException {
FileInputStream fi = new FileInputStream("abc.xls");
ArrayList<EmployeeVo> al = new ArrayList<>();
EmployeeVo evo = null;
Scanner scanner = null;
Workbook wb = new XSSFWorkbook(fi);
Sheet sh = wb.getSheet("Sheet0");
int starRow = sh.getFirstRowNum();
int endRow = sh.getLastRowNum();
for (int i = starRow + 1; i < endRow; i++) {
scanner = new Scanner(System.in);
evo = new EmployeeVo();
Cell c = wb.getSheetAt(0).getRow(i).getCell(1);
evo.setEmployeeId((int) c.getNumericCellValue());
Cell c2 = wb.getSheetAt(0).getRow(i).getCell(2);
evo.setEmployeeName(c2.toString());
// add to collection
al.add(evo);
} // for
al.forEach(i -> {
System.out.println(i.getEmployeeId() + " " + i.getEmployeeName());
});
}
}

How do I use cell values from an Excel worksheet as input?

I need to write a code that will go through a sheet of an Excel file (.xlsx)
and then use those values from the cell one by one via WebDriver.
To be more specific, one sheet holds search engines links and another sheet holds queries.
I only need you to help me figure out how to use the links from the Excel file,
and not as hard coded values, a way to iterate through them.
This is what I have so far:
package a.utilities;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import a.utilities.ChromeDriverInit;
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;
import org.apache.poi.*;
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;
import org.openqa.selenium.WebDriver;
public class ExcelUtils {
static WebDriver driver;
protected static XSSFSheet excelWSheet;
protected static XSSFWorkbook excelWBook;
private static XSSFCell cell;
private static XSSFRow row;
//
static String web;
static String query;
// Setting the file to read from
public static void setExcelFile() throws FileNotFoundException {
FileInputStream file = null;
try {
file = new FileInputStream("ExcelWorkSheets/SearchEngines.xlsx");
excelWBook = new XSSFWorkbook(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Counting the used rows in every work sheet and give you the work sheets data
public static void getSheetData() {
int index = 0;
for (int i = 0; i < excelWBook.getNumberOfSheets(); i++) {
index++;
System.out.println("Sheet Name: " + "["
+ excelWBook.getSheetName(i) + "] --> " + "Sheet index: "
+ "[" + index + "]\n");
}
int rowIndex = 0;
for (int i = 0; i < excelWBook.getSheetAt(0).getLastRowNum()+1; i++) {
excelWSheet = excelWBook.getSheetAt(0);
rowIndex++;
}
System.out.println("Number of rows including the header: --> " + rowIndex);
System.out.println("Number of rows not including the header: --> " +excelWSheet.getLastRowNum());
System.out.println();
int rowIndex2 = 0;
for (int i = 0; i < excelWBook.getSheetAt(1).getLastRowNum()+1; i++) {
excelWSheet = excelWBook.getSheetAt(1);
rowIndex2++;
}
System.out.println("Number of rows including the header: --> " + rowIndex2);
System.out.println("Number of rows not including the header: --> " +excelWSheet.getLastRowNum());
System.out.println();
// Going through the SearchEngines work sheet to get the data from every used cell and prints it out
Iterator<Row> rowIterator = excelWSheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue() + "\t\t");
case Cell.CELL_TYPE_STRING:
web = cell.getStringCellValue();
System.out.println(web + "\t\t");
default:
break;
}
}
System.out.println("");
}
// Going through the queries work sheet to get the data from every used cell and prints it out
Iterator<Row> rowIterator2 = excelWSheet.iterator();
while(rowIterator2.hasNext()) {
Row row = rowIterator2.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue() + "\t\t");
break;
default:
break;
}
}
System.out.println("");
}
}
This does go through the list, but how do I pass it on so WebDriver would be able to use this values?
So try to write the program so that one value is read from the file. Store that value in a java variable and use this variable as required with webdriver. Then iterate over it as required.
I think the flow should be like this.
Read the xlsx file value with search engines (Iteration on Search Engines)
use get to open the url
iterate over the queries
Repeat for next search engins
Lets say the values which you are fetching from an excel file are name and mail-id.
Store both the values in their Data-type variables.
Lets say name and mailid are the two required variables.
Now create one method with the parameters created above to send it to web-page from Excel file.
Below is just the sample implementation how you can do it.
public static void runTest(String name,String mailid) throws InterruptedException
{
System.out.println("Inputing name: "+name+" and mailid: "+mailid);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).clear();
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).clear();
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).sendKeys(name);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).sendKeys(mailid);
System.out.println("Inputted name: "+name+" and mailid: "+mailid);
Thread.sleep(2000); // Sleeping 2 seconds so that each entry is detected.
}
}
Save values in a datastructure.
Iterate through the values.
Create a helper function which will pass value one by one in to Web driver.
Pseudocode:-
//Instead of printing the values
//Save all the site in
List<String> sites = new ArrayList<String>(0);
//Save all the queries in
List<String> queries = new ArrayList<String>(0);
for(String site : sites){
System.out.println("Time consumed:- " + runQueriesForSite(site, queries));
}
private int runQueriesForSite(site, queries){
int searchTime = 0;
for(String query : queries) {
searchTime += runQueryForSite(query, site); //Webdriver will use this function to connect and return result
}
return searchTime;
}
int runQueryForSite(query, site)
{
//Hope you'll find the time calculation algorithm yourself
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get(site);
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys(query);
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}

Categories