Compare 2 Excel data if same column name having different postion - java

I want to compare two excel sheet data with same column name, excel sheet having same column name but position of column name will be different. So, I need logic first check column name and compare data
below code is working if both the sheet column name have same position or index.
public static void main(String[] args) throws IOException {
// Workbook1 Code
FileInputStream filepath1 = new FileInputStream(".\\DataFile\\Book1.xlsx");
XSSFWorkbook workbook1 = new XSSFWorkbook(filepath1);
XSSFSheet worksheet1 = workbook1.getSheet("sheet1");
int rowcount1 = worksheet1.getPhysicalNumberOfRows();
int CellCount=worksheet1.getRow(0).getPhysicalNumberOfCells();
System.out.println("row count of worbook1:" + rowcount1);
// Workbook2 Code
FileInputStream filepath2 = new FileInputStream(".\\DataFile\\Book2.xlsx");
XSSFWorkbook workbook2 = new XSSFWorkbook(filepath2);
XSSFSheet worksheet2 = workbook2.getSheet("sheet1");
int rowcount2 = worksheet2.getPhysicalNumberOfRows();
System.out.println("row count of worbook2:" + rowcount2);
if (rowcount1 == rowcount2) // condition if rowcount1 is equal to row count of worbook2 are same
{
for (int i = 0; i < rowcount1; i++) {
for(int j=0; j<CellCount; j++)
{
XSSFCell row1 = worksheet1.getRow(i).getCell(j);
XSSFCell row2 = worksheet2.getRow(i).getCell(j);
row1.setCellType(CellType.STRING);
String cellvalue=row1.getStringCellValue();
row2.setCellType(CellType.STRING);
String cellvalue2=row2.getStringCellValue();
if(!cellvalue.equals(cellvalue2))
{
System.out.println("Row number:"+i+ " Column number:"+j+" [ERROR] :" + "Diference in data " +"| Book1 id = " + cellvalue + " | Book2 id = " + cellvalue2);
}
}}}

Related

How can I compare console output with excel sheet data using selenium webdriver?

I have retrieved the elements of a table to the console window and I would like to compare the output with data present in an excel sheet. Can anyone please help me with this?
// To locate table.
WebElement mytable = driver.findElement(By.xpath("//*[#id=\ejSearchResultTable\"]"));
// To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
// To calculate no of rows In table.
int rows_count = rows_table.size();
// Loop will execute till the last row of table.
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
// To calculate no of columns (cells). In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are " + columns_count);
// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out
.println("Cell Value of row number " + row + " and column number " + column + " Is " + celtext);
}
}
Reading data from Excel:
String path = "C:\\Users\\Desktop\\ExportExcel.xlsx";
FileInputStream fis = new FileInputStream(path);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i=0; i<Rowcount+1 ; i++)
{
Row row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++)
{
System.out.println("Cell Value of row number " + i + " and column number " + j+ " Is " + row.getCell(j).getStringCellValue());
}

want to print a particular cell's all the row values in excel in java

After getting a paticular item name and price I store it in excel sheet. Now I compare their price and get lowest price, but how can i print that lowest price all detail
my code is
public static void getMinPhonePrice() throws Exception {
File file = new File("C:\\Users\\user\\Desktop\\demo.xlsx");
FileInputStream fs = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(fs);
String min = wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue();
int value_min = Integer.parseInt(min.substring(1).replace(",", ""));
String getText = null;
XSSFSheet sh1= wb.getSheetAt(0);
for(int j=0;j<3;j++) {
getText = sh1.getRow(0).getCell(j).getStringCellValue();
System.out.println(getText);
}
for (int i = 1; i <=sh1.getLastRowNum(); i++) {
String c = sh1.getRow(i).getCell(1).getStringCellValue();
int value = Integer.parseInt(c.substring(1).replace(",", ""));
if(value < value_min) {
value_min=value;
for(int k=0;k<3;k++) {
getText = sh1.getRow(i).getCell(k).getStringCellValue();
System.out.println("minimum item detail"+getText);
}
}
}
}
}
but it not printing my minimum item detail
It seems like you don't need nested loop, and you need store other cell to string variable. Please try the bellow code.
File file = new File("phone_compare.xlsx");
FileInputStream fs = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(fs);
String min = wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue();
int value_min = Integer.parseInt(min.substring(1).replace(",", ""));
String getText = null;
String str1 = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue();
String str2 = wb.getSheetAt(0).getRow(0).getCell(2).getStringCellValue();
getText = str1 +" " +value_min +" " +str2;
XSSFSheet sh1= wb.getSheetAt(0);
for (int i = 0; i <=sh1.getLastRowNum(); i++) {
String c = wb.getSheetAt(0).getRow(i).getCell(1).getStringCellValue();
int value = Integer.parseInt(c.substring(1).replace(",", ""));
if(value < value_min) {
value_min=value;
str1 = wb.getSheetAt(0).getRow(i).getCell(0).getStringCellValue();
str2 = wb.getSheetAt(0).getRow(i).getCell(2).getStringCellValue();
getText = str1 +" " +value_min +" " +str2;
}
}
System.out.println(getText);
}

Write to excel file using apache poi using selenium

Please before you down vote this, I was not able to find an example of reading a web table and writing it to an Excel file. If you happen to find that link kindly provide it. I have found plenty of examples on how to write to an Excel file but without reading from web table part.
Here is my code:
public class WebTable1 {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/html/html_tables.asp");
//tr means Row, this table has 7 rows including Header
///td means Column, this table has 3 columns
//*[#id="customers"]/tbody/tr[2]/td[1]
//*[#id="customers"]/tbody/tr[7]/td[1]
//Notice above the pattern, only the values are changing for tr[??]- which is why we will break it down into 2 String
//below and then concatinate them as String
String beforeXpath_Company = "//*[#id='customers']/tbody/tr["; // changed customer to single quote
String aferXpath_Company = "]/td[1]"; //Company is column 1
String beforeXpath_Contact = "//*[#id='customers']/tbody/tr[";
String aferXpath_Contact = "]/td[2]"; // Contact is column 2
String beforeXpath_Country = "//*[#id='customers']/tbody/tr[";
String aferXpath_Country = "]/td[3]"; // Country is column 3
//Find number of rows so that we do not use hard coded values
List<WebElement> totalRows = driver.findElements(By.xpath("//table[#id='customers']//tr"));
int rows=totalRows.size();
for (int i = 2; i <rows; i++) { //we start from 2 because 1 is column name
String actualXpath = beforeXpath_Company + i + aferXpath_Company;
String companyName = driver.findElement(By.xpath(actualXpath)).getText();
System.out.println(companyName);
String actualXpath_Contact = beforeXpath_Contact + i + aferXpath_Contact;
String contactName = driver.findElement(By.xpath(actualXpath_Contact)).getText();
System.out.println(contactName);
String actualXpath_Country = beforeXpath_Country + i + aferXpath_Country;
String countryName = driver.findElement(By.xpath(actualXpath_Country)).getText();
System.out.println(countryName);
//Try to following to write to an Excel file in C drive
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet("Sheet1");
Row row = sheet1.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(createHelper.createRichTextString(companyName));
FileOutputStream fileOut = new FileOutputStream("C:\\MyTemp\\Test.xls");
wb.write(fileOut);
fileOut.close();
}
}
}
Thanks in advance.
Taking your existing table extraction code, you can do something like this:
public class WebTable1 {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/html/html_tables.asp");
String beforeXpath_Company = "//*[#id='customers']/tbody/tr["; // changed customer to single quote
String aferXpath_Company = "]/td[1]"; //Company is column 1
String beforeXpath_Contact = "//*[#id='customers']/tbody/tr[";
String aferXpath_Contact = "]/td[2]"; // Contact is column 2
String beforeXpath_Country = "//*[#id='customers']/tbody/tr[";
String aferXpath_Country = "]/td[3]"; // Country is column 3
//Find number of rows so that we do not use hard coded values
List<WebElement> totalRows = driver.findElements(By.xpath("//table[#id='customers']//tr"));
int rows=totalRows.size();
// Create a workbook and a sheet in it
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("Sheet1");
// Create a table header
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("Company name");
row.createCell(1).setCellValue("Contact name");
row.createCell(2).setCellValue("Country");
for (int i = 2; i <rows; i++) { //we start from 2 because 1 is column name
String actualXpath = beforeXpath_Company + i + aferXpath_Company;
String companyName = driver.findElement(By.xpath(actualXpath)).getText();
String actualXpath_Contact = beforeXpath_Contact + i + aferXpath_Contact;
String contactName = driver.findElement(By.xpath(actualXpath_Contact)).getText();
String actualXpath_Country = beforeXpath_Country + i + aferXpath_Country;
String countryName = driver.findElement(By.xpath(actualXpath_Country)).getText();
Row row = sheet1.createRow(i - 1);
row.createCell(0).setCellValue(companyName);
row.createCell(1).setCellValue(contactName);
row.createCell(2).setCellValue(countryName);
}
FileOutputStream fileOut = new FileOutputStream("C:\\MyTemp\\Test.xls");
wb.write(fileOut);
fileOut.close();
}
}

Find last row no in excel in a particular columnno using Apache poi

i want to find the row no i.e 10 of value "sam" using columnno 6
any inbuilt function in apache poi like this col(6).getLastRowNum()
Try below code to identify last row from excelsheet. Below code automatically iterate through all rows and identify last row from all columns.
public static void main(String[] args) throws IOException {
// Making of excel file object
File myFile = new File(CommonMethods.getFilePath("testdata", "Sample.xlsx"));
FileInputStream fis = new FileInputStream(myFile);
XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);
XSSFSheet mySheet = myWorkBook.getSheet("Logout");
XSSFRow row = null;
// Making the object of excel row
row = mySheet.getRow(0);
int colCount = row.getLastCellNum();
System.out.println("Column Count :- " + colCount);
int rowCount = mySheet.getLastRowNum() + 1;
System.out.println("Row Count :- " + rowCount);
}

Fetching value from webtable and write in excel sheet one by one of each row in a loop

1) I am trying to read the values from the webtable of an appliation and write it into the excel sheet one by one.
2) There are 4 values in each row of the webtable that need to be written to excel sheet, but there are some images in each row that i'm ignoring bu using below code.
text.length()>2
.
3) There will be 200-300 rows in webtable that need to be fetched and written to excel sheet.
This is the code i have tried. But i dont know how to write it into each row of the excel sheet one by one. Please help me in this regard.
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
for (WebElement row : allRows) {
//Get all cell values in each row
List<WebElement> allCells = row.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1){
for (WebElement cell : allCells) {
String text = cell.getText();
if(text.length()>2){
String value = cell.getText();
}
}
}
// locate the test xl file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row = sheet1.getRow(1);
HSSFCell cellEx = row.getCell(0);
if (cellEx == null) {
cellEx = row.createCell(0);
}
cellEx.setCellValue(value);
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
// locate the test xls file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row;
for (int i=0; i<rowSize; i++)
{
WebElement webRow = allRows.get(i);
//Get all cell values in each row
List<WebElement> allCells = webRow.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1)
{
HSSFRow excelRow = sheet1.createRow(i);
for (int j=0; j<allCells.size(); j++)
{
WebElement webCell = allCells.get(j);
String text = webCell.getText();
if(text.length()>2)
{
Cell excelCell = excelRow.createCell();
excelCell.setValue(webCell.getText());
}
}
}
}
sheet1.close();
Read the values from the Web Table of an application and write it in to the excel sheet one by one.There are 5 values in each row of the Web Table and that need to written in Excel sheet. Below is the working code.
System.setProperty("webdriver.chrome.driver","C:\\Users\\Documents\\Selenium jars\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://cosmocode.io/automation-practice-webtable/");
WebElement table = driver.findElement(By.xpath("//*[#id='countries']/tbody"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
int rowcount = rows.size();
FileOutputStream fis = new FileOutputStream(new File("C:\\Users\\Documents\\Selenium\\output.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet("First Sheet");
for (int row = 0; row < rowcount; row++) {
List<WebElement> columns_inrow = rows.get(row).findElements(By.tagName("td"));
int columns_count = columns_inrow.size();
System.out.println("Number of cells in Row " + row + " are " + columns_count);
Row ro = sh.createRow(row);
for (int column = 0; column < columns_count; column++) {
String celltext = columns_inrow.get(column).getText();
System.out.println(
"Cell Value of row number " + row + " and column number " + column + " Is " + celltext);
ro.createCell(column).setCellValue(celltext);
}
System.out.println("===========================");
}
wb.write(fis);
wb.close();
}

Categories

Resources