I have imported my excel file but i want to check duplicate cells in excel sheet .
I want to check each cell read and duplicate cell display alert message in jsp page.
Iterator obj = new Itertor();
StringBuffer sb = new StringBuffer();
while(obj.hasNext()) {
Row myrow = (ROW) obj.next();
class obj1 = new class();
obj1.setname();
}
I don't really understand your data structure. Are you using Apache POI? How are you obtaining the values from excel?
To identify duplicates create a HashSet and start adding values to the set. Add method returns true if the value was added. False otherwise.
Iterator sheetInterator = new Itertor();
Set<Object> set = new HashSet();
while(sheetInterator.hasNext()) {
Row myrow = (Row) obj.next();
Iterator rowIterator = myrow.iterator();
while(rowIterator.hasNext()) {
Cell cell = (Cell) rowIterator.next();
String value = cell.getValue();
if(!set.add(value)){
// value has not been added to the set -> it is at least 2nd occurrence of this value
}
}
}
Related
I am reading cells from an Excel spreadsheet. I am reading the first cell in each row, and comparing them to a String object that I have passed into the function. The function correctly iterates over all rows and accesses the first cell in each row, but when comparing them to the String object parameter, the IF statement does not execute, despite both the value obtained from the cell and the String parameter printing the same thing. I have used '==' operators, as well as .equals() but nothing seems to let the IF statement execute.
public static ArrayList<Integer> returnCurrency(String currency, String fileName) throws IOException
{
FileInputStream excelFile = new FileInputStream(newFile(fileName));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
ArrayList<Double> currencyRateArray = new ArrayList<Double>();
for( int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++)
{
Row row = sheet.getRow(rowNum);
Cell tempCell = row.getCell(0);
System.out.printf("temp cell has value of:%s\n",tempCell.getStringCellValue());
System.out.printf("currency variable is: %s\n", currency);
if(currency.equals(tempCellString))
{
System.out.println("Found the currency\n");
}
}
}
When I pass the parameter String as "USD", both print statements print "USD", but it will never print "Found the currency" as that IF statement does not execute. Any help would be appreciated :)
Found the answer - the cell in the database had the value 'USD ' instead of 'USD'.
Using a list of strings, I am trying to match the string in a excel sheet and add the cell elements in the inner list. Adding the inner list in the outer list using a loop. Please refer the code below
public static List<ArrayList<String>> getKeywords(List<String> testCaseIdList, String fileName, String sheetName){
try {
ArrayList<String> listTestSteps = new ArrayList<String>();
List<ArrayList<String>> listTestCases = new ArrayList<ArrayList<String>>(0);
Sheet sheetKW = ReadExcelFile.readExcel(ST_KEYWORDS);
String columnValue = null;
int matchFlag, addListFlag = 0;
for(String testCaseId : testCaseIdList) {
Iterator<Row> rowIterator = sheetKW.rowIterator();
listTestSteps.clear();
while(rowIterator.hasNext()) {
Row rowNext = (Row) rowIterator.next();
Iterator<Cell> cellIterator = rowNext.cellIterator();
matchFlag = 0;
addListFlag = 0;
//listTestSteps.clear();
while(cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
columnValue = nextCell.getStringCellValue();
//System.out.println("Column value " +columnValue);
if((columnValue.equalsIgnoreCase(testCaseId)) && (columnValue != "" )) {
matchFlag = 1;
}
if(matchFlag == 1 && columnValue != "") {
listTestSteps.add(columnValue);
addListFlag = 1;
System.out.println("Add Value : "+columnValue);
}
}
if((listTestSteps.isEmpty() == false) && (addListFlag == 1)) {
System.out.println("Adding to the Main list");
listTestCases.add(listTestSteps);
//listTestCases.forEach(System.out::println);
}
}
}
//listTestSteps.forEach(System.out::println);
// Return ArrayList of ArrayLists
return listTestCases;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I am getting the output as
[TC_0003, login, createUser, deleteUser]
[TC_0003, login, createUser, deleteUser]
Firstly added list listTestSteps is getting replaced by the last iteration list.
Expected output is
[[TC_0002, login, createUser, deleteUser, newUser], [TC_0003, login, createUser, deleteUser]]
Something is wrong for sure. Any help will be appreciated.
Using the
listTestSteps.clear();
instruction in the loop lets you use always the same list, so in every iteration you just empty and refill the same list and add it to the outer list. For this reason the outer list will at the end contain x entries pointing always at the same list, which is filled with the data you put there in last iteration.
So you just have to do
ArrayList<String> listTestSteps = new ArrayList<String>();
instead of clearing the list
The problem is you add the reference of listTestSteps to listTestCases and then in the next loop you clear the listTestSteps, but the cleared list is still referenced in listTestCases. So would suggest using the answer to Add an object to an ArrayList and modify it later to ensure that both lists are resolved properly.
I using Apache poi to import an .xlsx file that I have in my desktop area.
With the below code I can read the hole sheet that I want.
But I want to read only one line per time and only specific columns per line (for example I want only column A, F and G from the first line and save it as object, then the same for the second line, third line etc )
How can I do it?
public class main {
public static void main( String[] args ) throws Exception {
InputStream ExcelFileToRead = new FileInputStream("C:/User/Desktop/test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
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();
}
}
}
A specific row can be retrieved from the Sheet object using
Sheet.getRow(index)
Where index is a zero based row number. That is, to read row 1, you must get the row at index zero, row 2 is at index 1 and so on. Similarly a specific cell can be retrieved from it's Row object using
Row.getCell(index)
Once again index is a zero based cell number where cell column A is at index 0, column B is at index 1 and so on. Therefore to retrieve the Cell at B2, you could use
Cell cell = Sheet.getRow(1).getCell(1);
What I am trying to do is simply print multiple values using for loop and arraylist from multiple columns with the following code
// =========The SpreadSheet=========
File src = new File("J:\\Excel files\\mutiselect.xlsx");
// Load file
FileInputStream fis = new FileInputStream(src);
// Load WB
XSSFWorkbook wb = new XSSFWorkbook(fis);
// Load Sheet
XSSFSheet sh1 = wb.getSheetAt(0);
List<String> values = new ArrayList<String>(); //values from excel will be stored within this array
Iterator<Row> rows = sh1.rowIterator();
while (rows.hasNext())
{
Row row = rows.next();
if (row.getRowNum() > 0)
{
values.add(row.getCell(1).getStringCellValue());
}
}
System.out.println(values);
Thread.sleep(2000);
List<String> values2 = new ArrayList<String>(); //values from excel will be stored within this array
Iterator<Row> rows2 = sh1.rowIterator();
while (rows2.hasNext())
{
Row row2 = rows2.next();
if (row2.getRowNum() > 0)
{
values2.add(row2.getCell(2).getStringCellValue());
}
}
System.out.println(values2);
fis.close();
driver.quit();
Everything works fine it there is matching number of records within excel on Column B and Column C.
But the problem occurs and it doesn't print from one of the columns or from both columns when there is no match between the number of rows that has values means if there is more value on column B than Column C, or More value on Column C than B it will not print.
Please refer to this image for illustration:
http://i.imgur.com/DO8anzu.png
If the excel is like this the values from one of the columns doesnt get printed or from both columns nothing get printed
and gives me error like this
Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:57)
Line#57 refers to this code
values.add(row.getCell(1).getStringCellValue());
or gives me this error
Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:99)
line#99 refers to this code
values2.add(row2.getCell(2).getStringCellValue());
What I want to do is print out all the values from each column individually even even if there is no match in number of values or its less or more in one column than the other
to do this where do I change in the code please?
P.S this code is being used for Selenium Webdriver with Java
From getCell() documentation
If you ask for a cell that is not defined....you get a null.
When the number of values is different in each column the Iterator still has next line so rows.hasNext() is true, but the cell is empty so row.getCell(1) is null.
When you try to get getStringCellValue() from the null cell you get NullPointerException.
Change
if (row.getRowNum() > 0)
To
if (row.getRowNum() > 0 && row.getCell(1) != null)
What about checking for null before adding to the values and values2 lists?
if(row.getCell(1) != null) {
values.add(row.getCell(1).getStringCellValue());
}
and
if(row2.getCell(2) != null) {
values.add(values2.getCell(2).getStringCellValue());
}
I am populating a template Excel sheet, with the data from the database :
for (Map<String, Object> resultRow : dbResults) {
if ((currentRow = sheet.getRow(currentDataRow)) == null) {
currentRow = sheet.createRow(currentDataRow); // Creates a new row.
}
//currentRow.getRowStyle().setHidden(false);
for (int i = 0; i < resultColumns; i++) {
currentCell = currentRow.getCell(i, Row.CREATE_NULL_AS_BLANK);
setCellValue(currentCell, resultRow.get(dbcolumnNames[i]));
}
currentDataRow += 1;
}
// How to hide all empty/Un-used rows following currentDataRow ?
Aim to Achieve :
I want that the Un-Used rows following the populated rows should be hidden ?
All Populated rows must be visible.
Eg: If 1st 100 data rows are filled, then rows following 101 and onward should be hidden.
Please, help !!
Row r = sheet.getRow(indexRow);
if ( r!=null ) {
r.setZeroHeight(true);
}
POI recognizes the number of logical rows in your sheet when you create it.
So as you populate it with 100 rows, it will create 100 records. The rest will appear when you open the XLS in Excel with the default layout - but these are not POI records.
You'll have to create some dummy rows after your last data record like this
for (int i=currentDataRow ;i<65000;i++)
sheet.createRow(i);
Create a cell style, and set it to hidden
CellStyle hiddenstyle = workBook.createCellStyle();
hiddenstyle.setHidden(true);
Set this style for all rows from your last row to end of sheet
while (rows.hasNext()){
Row row1 = rows.next ();
row1.setRowStyle(hiddenstyle);
}
row.setRowStye() and row.getRowStye() are present in poi-3.8-beta4.