Selenium Data driven test- number read as decimal from excel - java

In the test some fields accepts numbers and it has been given in the excel. But when the data is read from the excel, it reads as decimals. for example number 22 is read as 22.0. I have used apache.poi for the test. How to avoid decimal.
public static void main(String[] args) throws InterruptedException {
try{
FileInputStream input = new FileInputStream("C:Users\\dinu\\Desktop\\RegDetails.xls");
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheet("RegDetails");
for(int count =1; count <= sheet.getLastRowNum(); count++){
HSSFRow row = sheet.getRow(count);
System.out.println("Running Test Case "+row.getCell(0).toString());
runTest(row.getCell(1).toString(),row.getCell(2).toString(),row.getCell(3).toString(),
row.getCell(4).toString(),row.getCell(5).toString(),row.getCell(6).toString(),
row.getCell(7).toString(),row.getCell(8).toString());
}input.close();
}catch (IOException e){
System.out.println("Test data not found.");
}

Use this,it will work...
for (int i = 0; i < sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i + 1);
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
Cell cell = row.getCell(k);
String value;
try {
value = cell.getRichStringCellValue().toString();
} catch (Exception e) {
value = ((XSSFCell) cell).getRawValue();
}
data[i][k] = value;
}

Related

Unable to write new excel using Apache POI after removing duplicate rows

I am new to Apache POI.
I have written a small code for removing duplicate records from a excel file. I am successfully able to identify the duplicate records across sheets but when writing to a new file after removing records, no output is being generated.
Please help where I am goin wrong?
Am I writing properly ?? Or am missing something?
public static void main(String args[]) {
DataFormatter formatter = new DataFormatter();
HSSFWorkbook input_workbook;
HSSFWorkbook workbook_Output_Final;
HSSFSheet input_workbook_sheet;
HSSFRow row_Output;
HSSFRow row_1_index;
HSSFRow row_2_index;
String value1 = "";
String value2 = "";
int count;
//main try catch block starts
try {
FileInputStream input_file = new FileInputStream("E:\\TEST\\Output.xls"); //reading from input file
input_workbook = new HSSFWorkbook(new POIFSFileSystem(input_file));
for (int sheetnum = 0; sheetnum < input_workbook.getNumberOfSheets(); sheetnum++) { //traversing sheets
input_workbook_sheet = input_workbook.getSheetAt(sheetnum);
int input_workbook_sheet_total_row = input_workbook_sheet.getLastRowNum(); //fetching last row nmber
for (int input_workbook_sheet_row_1 = 0; input_workbook_sheet_row_1 <= input_workbook_sheet_total_row; input_workbook_sheet_row_1++) { //traversing row 1
for (int input_workbook_sheet_row_2 = 0; input_workbook_sheet_row_2 <= input_workbook_sheet_total_row; input_workbook_sheet_row_2++) {
row_1_index = input_workbook_sheet.getRow(input_workbook_sheet_row_1); //fetching one iteration row index
row_2_index = input_workbook_sheet.getRow(input_workbook_sheet_row_2); //fetching sec iteration row index
if (row_1_index != row_2_index) {
count = 0;
value1 = "";
value2 = "";
for (int row_1_index_cell = 0; row_1_index_cell < row_1_index.getLastCellNum(); row_1_index_cell++) { //traversing cell for each row
try {
value1 = value1 + formatter.formatCellValue(row_1_index.getCell(row_1_index_cell)); //fetching row cells value
value2 = value2 + formatter.formatCellValue(row_2_index.getCell(row_1_index_cell)); //fetching row cells value
} catch (NullPointerException e) {
}
count++;
if (count == row_1_index.getLastCellNum()) {
if (value1.hashCode() == value2.hashCode()) { //remove the duplicate logic
System.out.println("deleted : " + row_2_index);
System.out.println("------------------");
input_workbook_sheet.removeRow(row_2_index);
}
}
}
}
}
}
}
FileOutputStream fileOut = new FileOutputStream("E:\\TEST\\workbook.xls");
input_workbook.write(fileOut);
fileOut.close();
input_file.close();
} catch (Exception e) {
//e.printStackTrace();
}
//main try catch block ends
}
A couple of things to note:
you swallow any kind of Exception; Igotsome nullpointers with my test data, and that would prevent the workbook from being written
when removing rows, it is an old trick to move backwards through the row numbers because then you don't have to adjust for the row number you have just removed
the code empties the row, but it doesn't move all rows upwards (=there is a gap after the delete). If you want to remove that gap, you can work with shiftRows
you compare things by hashcode, which is possible (in some use cases), but I feel like .equals() is what you want to do. See also Relationship between hashCode and equals method in Java
Here's some code that worked for my test data, feel free to comment if something doesn't work with your data:
public static void main(String args[]) throws IOException {
DataFormatter formatter = new DataFormatter();
HSSFWorkbook input_workbook;
HSSFWorkbook workbook_Output_Final;
HSSFSheet input_workbook_sheet;
HSSFRow row_Output;
HSSFRow row_1_index;
HSSFRow row_2_index;
String value1 = "";
String value2 = "";
int count;
FileInputStream input_file = new FileInputStream("c:\\temp\\test.xls");
input_workbook = new HSSFWorkbook(new POIFSFileSystem(input_file));
for (int sheetnum = 0; sheetnum < input_workbook.getNumberOfSheets(); sheetnum++) {
input_workbook_sheet = input_workbook.getSheetAt(sheetnum);
int input_workbook_sheet_total_row = input_workbook_sheet.getLastRowNum();
for (int input_workbook_sheet_row_1 = input_workbook_sheet_total_row; input_workbook_sheet_row_1 >=0; input_workbook_sheet_row_1--) { // traversing
for (int input_workbook_sheet_row_2 = input_workbook_sheet_total_row; input_workbook_sheet_row_2 >= 0 ; input_workbook_sheet_row_2--) {
row_1_index = input_workbook_sheet.getRow(input_workbook_sheet_row_1);
row_2_index = input_workbook_sheet.getRow(input_workbook_sheet_row_2);
if (row_1_index != null && row_2_index != null && row_1_index != row_2_index) {
count = 0;
value1 = "";
value2 = "";
int row_1_max = row_1_index.getLastCellNum() - 1;
for (int row_1_index_cell = 0; row_1_index_cell < row_1_max; row_1_index_cell++) {
try {
value1 = value1 + formatter.formatCellValue(row_1_index.getCell(row_1_index_cell));
value2 = value2 + formatter.formatCellValue(row_2_index.getCell(row_1_index_cell));
} catch (NullPointerException e) {
e.printStackTrace();
}
count++;
if (value1.equals(value2)) {
System.out.println("deleted : " + row_2_index.getRowNum());
System.out.println("------------------");
input_workbook_sheet.removeRow(row_2_index);
input_workbook_sheet.shiftRows(
row_2_index.getRowNum() + 1,
input_workbook_sheet_total_row,
-1,
true,
true);
}
}
}
}
}
}
FileOutputStream fileOut = new FileOutputStream("c:\\temp\\workbook.xls");
input_workbook.write(fileOut);
fileOut.close();
input_file.close();
input_workbook.close();
}

read multiple excel sheet selenium-webdriver, java, eclipse

I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.

Apache POI - Reading excel file in 2D array - returning null values

I am trying to read Excel -2*2 matrix through Apache POI. But the first value returned by 2D array is [null,null]. Please check my code and advise for suitable corrections.
public String[][] getDataArray(String sheetName)
{
String value ="";
String[][] data = null;
int rowCount = wb.getSheet(sheetName).getLastRowNum();
int colCount = wb.getSheet(sheetName).getRow(1).getLastCellNum()-1;
data = new String[rowCount][colCount];
for(int i=1; i<=rowCount;i++)
{
Row row = wb.getSheet(sheetName).getRow(i);
for(int j=0;j<colCount;j++)
{
Cell cell = row.getCell(j);
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
{
value = ""+cell.getStringCellValue();
}
else
{
value = cell.getStringCellValue();
}
data[i][j] = value;
}
}
return data;
}
The debug view where we can see that the first value stored in the variable data is null, null
The excel which i am trying to read. I need only the userName and password data(2*2) alone. Not the header and Run mode datas.
Of course the value in the index 0 will be null because the i starts from 1 and not 0
for (int i = 1; i <= rowCount; i++) //i starts from one
...
data[i][j] = value;
either initialize the i from 0 or do like this
data[i-1][j] = value;
public static String[][] getSheetData(final String fileName, final String workSheetName)
throws Exception {
Integer lastRow = null;
short lastCol = 0;
String[][] sheetData = null;
FileInputStream file=new FileInputStream(MettlTest.class.getClass().getResource("/" + fileName).getPath());
workbook = new XSSFWorkbook(file);
sheet = workbook.getSheet(workSheetName);
try {
XSSFRow row;
XSSFCell cell;
lastRow = sheet.getPhysicalNumberOfRows();
lastCol = sheet.getRow(1).getLastCellNum();
sheetData = new String[lastRow - 1][lastCol];
for (int r = 1; r < lastRow; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c < lastCol; c++) {
cell = row.getCell(c);
if (cell == null) {
sheetData[r][c] = null;
} else {
sheetData[r-1][c] = new DataFormatter().formatCellValue(cell);
}
}
}
}
return sheetData;
}
catch (final Exception e) {
throw e;
}
finally {
try {
file.close();
} catch (IOException io) {
Reporter.log("Unable to close File : " + fileName);
throw io;
}
}

IndexOutOfBoundsException when using the write method on a Apache POI HSSFWorkbook

I'm trying to write a method that takes two HSSFSheets (from two different HSSFWorkbooks that are imported via a FileChooser) and makes sure that the name of each Row of Sheet1 (as in the first cell of each row of Sheet1) has to be the same name as each Row of Sheet2. If it's not the case the method has to re-organize Sheet2 so as the names of each Row of Sheet2 should match those of Sheet1.
In the end the method should create and open a new excel file which should contain the reorganized Sheet2. And this is where the problem comes in
public void organizeSheets(HSSFSheet sheet1, HSSFSheet sheet2) throws FileNotFoundException, IOException {
HSSFWorkbook permutationWb = new HSSFWorkbook();
HSSFSheet permutationSheet = permutationWb.createSheet();
short noOfColumns;
HSSFRow testrow = sheet1.getRow(0);
short testcell = testrow.getLastCellNum();
noOfColumns = testcell;
int noOfRows = sheet1.getPhysicalNumberOfRows();
short noOfColumns2;
HSSFRow testrow2 = sheet2.getRow(0);
short testcell2 = testrow2.getLastCellNum();
noOfColumns2 = testcell2;
for (int i = 0; i < noOfRows; i++) {
if (!getValue(sheet1, 0, i).toString().equals(getValue(sheet2, 0, i).toString())) {
System.out.println(getValue(sheet1, 0, i));
System.out.println(getValue(sheet2, 0, i));
int j = 0;
while (!getValue(sheet1, 0, i).toString().equals(getValue(sheet2, 0, j).toString())) {
j = j + 1;
}
HSSFRow transitionRow1 = permutationSheet.createRow(0);
HSSFRow transitionRow2 = permutationSheet.createRow(1);
for (int l=0; l < noOfColumns2; l++) {
transitionRow1.createCell(l);
transitionRow1.getCell(l).setCellValue(getValue(sheet2, l, j));
//System.out.println(transitionRow1.getCell(l));
}
for (int p=0; p < noOfColumns2; p++) {
transitionRow2.createCell(p);
transitionRow2.getCell(p).setCellValue(getValue(sheet2, p, i));
}
for (int k=0; k < noOfColumns2; k++) {
sheet2.getRow(j).getCell(k).setCellValue(getValue(permutationSheet, k, 1).toString());
sheet2.getRow(i).getCell(k).setCellValue(getValue(permutationSheet, k, 0).toString());
}
}
}
sheet2.getWorkbook().write(new FileOutputStream("C:\\Users\\PC HP\\Desktop\\organized.xls"));
sheet2.getWorkbook().close();
Desktop.getDesktop().open(new File("C:\\Users\\PC HP\\Desktop\\organized.xls"));
}
getValue(sheet, row, column) allows me to get the value of the cell whose coordinates are in the arguments of the method.
Here's the error message I'm getting
Exception in thread "main" java.lang.IndexOutOfBoundsException: Block 33 not found
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.getBlockAt(NPOIFSFileSystem.java:486)
at org.apache.poi.poifs.filesystem.NPOIFSStream$StreamBlockByteBufferIterator.next(NPOIFSStream.java:169)
at org.apache.poi.poifs.filesystem.NPOIFSStream$StreamBlockByteBufferIterator.next(NPOIFSStream.java:142)
at org.apache.poi.poifs.filesystem.NDocumentInputStream.readFully(NDocumentInputStream.java:248)
at org.apache.poi.poifs.filesystem.NDocumentInputStream.read(NDocumentInputStream.java:150)
at org.apache.poi.poifs.filesystem.DocumentInputStream.read(DocumentInputStream.java:125)
at org.apache.poi.hpsf.PropertySet.isPropertySetStream(PropertySet.java:336)
at org.apache.poi.hpsf.PropertySet.<init>(PropertySet.java:241)
at org.apache.poi.hpsf.PropertySetFactory.create(PropertySetFactory.java:92)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:211)
at org.apache.poi.POIDocument.getPropertySet(POIDocument.java:168)
at org.apache.poi.POIDocument.readProperties(POIDocument.java:141)
at org.apache.poi.POIDocument.getSummaryInformation(POIDocument.java:108)
at org.apache.poi.POIDocument.writeProperties(POIDocument.java:260)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1377)
at model.main.organizeSheets(main.java:377)
at model.main.main(main.java:42)
Caused by: java.lang.IndexOutOfBoundsException: Unable to read 512 bytes from 17408 in stream of length -1
at org.apache.poi.poifs.nio.ByteArrayBackedDataSource.read(ByteArrayBackedDataSource.java:42)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.getBlockAt(NPOIFSFileSystem.java:484)
... 16 more
I believe that there is no problem with the actual switch between the rows of Sheet2 (I've tested with prints, I might be wrong if I didn't test enough) and I have no idea how to deal with this situation.
In order to instantiate Sheet2, the code asks the user to chose a workbook from his computer then choose a sheet within the workbook like follows
excelworkbook1 = o.chooseFile1();
Scanner scanner1 = new Scanner(System.in);
int sheetnumber1 = Integer.parseInt(scanner1.nextLine());
excelsheet1 = o.chooseSheet(excelworkbook1, sheetnumber1);
public HSSFWorkbook chooseFile1() throws IOException {
JFrame frame = null;
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frame);
String filepath = new String();
if (returnVal == JFileChooser.APPROVE_OPTION) {
filepath = fc.getSelectedFile().getCanonicalPath();
setFile1Adress(filepath);
} else {
System.exit(1);
}
FileInputStream file1InputStream;
file1InputStream = new FileInputStream(filepath);
NPOIFSFileSystem file;
file = new NPOIFSFileSystem(file1InputStream);
HSSFWorkbook workbook = new HSSFWorkbook(file.getRoot(), true);
file.close();
return workbook;
}
public HSSFSheet chooseSheet(HSSFWorkbook excelfile, int entry) {
return excelfile.getSheetAt(entry - 1);
}

Reading from excel file with blank cells to 2d array

I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}

Categories

Resources