0

I have an excel sheet from which I need to fetch the rows based on the cell value of a particular column. For example I have a column named city and employee_name. I will be providing city value using my Java code and it should fetch all the rows which have that city value in a specified column. Column name will be fixed.

Example:
City    Employee_Name Age
Vegas   Tom           23
Vegas   Ron           43
Vegas   Sam           19
Delhi   Rohit         32
Delhi   Ram           28
Jaipur  Ankit         31

So, if I give the cell value as Vegas from my Java code so it should fetch me the row 1,2 & 3.

3
  • I am newbie in Aapche POI and trying to learn it. I have developed small programs like reading excel cells and creating the cells. It will be really helpful if I can get some help as I am struck since yesterday. Commented Jun 15, 2013 at 5:47
  • 1
    Share whatever code you have tried. Commented Jun 15, 2013 at 5:51
  • using apache-poi you need to iterate and check for your city if city is found then add the value to different list Commented Jun 15, 2013 at 6:08

2 Answers 2

2

You can use following Method. "sheet" is the sheet in which you need to perform search, "colName" is the name of column, as per your requirement, it will be fixed. and "textToFind" is the text you have to find in colName column.

public static XSSFRow test(XSSFSheet sheet, String colName, String textToFind){
    int colIndex=0;
    for (int colNum = 0; colNum<=sheet.getRow(0).getLastCellNum();colNum++){
        if (sheet.getRow(0).getCell(colNum).toString().equalsIgnoreCase(colName)){
            colIndex = colNum;
            break;
        }
    }
    for (int RowNum = 0; RowNum<sheet.getLastRowNum();RowNum++){
        if(sheet.getRow(RowNum).getCell(colIndex).toString().equalsIgnoreCase(textToFind)){
            return sheet.getRow(RowNum);
        }
    }
    System.out.println("No any row found that contains "+textToFind);
    return null;
}
Sign up to request clarification or add additional context in comments.

4 Comments

the solution is correct but RowNum<sheet.getLastRowNum() will make you skip the last row the condition should be RowNum<=sheet.getLastRowNum()
No @NatherWebber... If sheet has 5 rows for example, then getLastRowNum() will return 5. But since the getRow(Num) is zero index based so the possible value that need to pass for Num will be 0, 1, 2, 3 and 4 but not 5 that is why RowNum<sheet.getLastRowNum() is correct
I tested and in my case getLastRowNum() with 5 rows will return 4 so I had to put that condition.
Updated as per @NatherWebber
1
  1. Put this in lib folder of ur project poi-2.5.1.jar
  2. Try to use this method in struts Action else u can simply use it in simple class avoiding/deleting HttpSession parameter from method arguments
  3. void uploadBulkQuestions(ExcelUploadForm excelUploadForm,String filePath,HttpSession session) throws SQLException//you can neglect ExcelUploadForm obj in parameters { ExcelForm excelForm=null; /** * //Here ExcelForm is a simple pojo with setters and getters * *public class ExcelForm extends ActionForm { *String city; *String employeeName; *Integer age; * //setters and getters of above variables. * } */ short CityPosition=0; short Employee_NamePosition=1; short AgePosition=2; Connection con=null; ArrayList invalidFields=new ArrayList(); ArrayList validFields=new ArrayList(); boolean bulkUploadFlag=true;

    try
    {
        FileInputStream fs =new FileInputStream(filePath+"\\"+excelUploadForm.getExcelFile().getFileName());//here you can give ur ExcelFile Path{like--"D:\ExcelFiles\sample.xls"}(excelUploadForm in method parameter is an another form which pics a file through browse(i.e.,File Upload))) 
    
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        for (int k = 0; k < wb.getNumberOfSheets(); k++)
        {
            HSSFSheet sheet = wb.getSheetAt(k);
            int rows  = sheet.getPhysicalNumberOfRows();
            HSSFRow firstRow   = sheet.getRow(0);
            int totalCells = firstRow.getPhysicalNumberOfCells(); 
            for(short i=0;i<totalCells;i++)
            {
                HSSFCell firstCell;
                firstCell=firstRow.getCell(i);
                     if(firstCell.getStringCellValue().trim().equalsIgnoreCase("City"))
                    {CityPosition=i;System.out.println("HSSFCellqidpos"+City);}
                else if(firstCell.getStringCellValue().trim().equalsIgnoreCase("Employee_Name"))
                    Employee_NamePosition=i;
                else if(firstCell.getStringCellValue().trim().equalsIgnoreCase("Age"))
                    AgePosition=i;
            }
    
            for (int r = 1; r < rows; r++)
            {
                excelForm = new ExcelForm();
                HSSFRow row   = sheet.getRow(r);
                HSSFCell cell;  
                if(CityPosition>=0)
                {
                    cell= row.getCell(CityPosition);
                    try{
                    excelForm.setCity(cell.getStringCellValue());
                    System.out.println("Check the Data of city"+excelForm.getCity());
                }catch(NullPointerException nullPointerException){
                    nullPointerException.printStackTrace();
                }
                }
    
                if(Employee_NamePosition>0)
                {
                    cell= row.getCell(Employee_NamePosition);
                    try{
                    excelForm.setEmployeeName(cell.getStringCellValue());
                }catch(NullPointerException nullPointerException){
                    nullPointerException.printStackTrace();
                }
                }
    
                if(AgePosition>0)
                {
                    cell= row.getCell(AgePosition);
                    try{
                    excelForm.setAge((int)cell.getNumericCellValue());
                }catch(NullPointerException nullPointerException){
                    nullPointerException.printStackTrace();
                }
                }
    
                //Validating Excel Data
                if(excelForm.getCity()==null || excelForm.getEmployeeName()==null || excelForm.getAge() < 0)
                {
                    System.out.println("inside invalidFields.........");
                    System.out.println(excelForm);
                    invalidFields.add(excelForm);
                    bulkUploadFlag=false;
                }
                else
                {   
                System.out.println("inside validQue.........");
                System.out.println(excelForm);  
                validFields.add(excelForm);
                }
    
            }
    
    
    
        }
    
    
    
    
        //Transaction Management to make sure all the validFields ArrayList obj data is inserted
    
        if(bulkUploadFlag)
        {
            con.setAutoCommit(false);
    
            try
            {
                //fetch data from validFields Array List Using iterator and insert into DB if u wish to do so...
                Iterator fieldsIterator=  validFields.iterator();
                excelForm =null;
                while(questionIterator.hasNext())
                    {
    
                    excelForm=(excelForm)fieldsIterator.next();                     
                        //storing in Questions DB table
                        PreparedStatement psFields = con.prepareStatement("........");//write ur query to insert
                        psFields.executeUpdate();
    
            }
    
            // If there is no error.
            con.commit();
            session.setAttribute("ValidFields", validFields);
    
            }
            catch(SQLException se)
            {
                // If there is any error.
                 con.rollback();
                 se.printStackTrace();
                 session.setAttribute("BulkUploadError","No Data Uploded due to Some Errors in Excel File");     
            }
        }
        else
        {
            session.setAttribute("InvalidFields",invalidFields);
    
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        con.close();
    }
    
    return null;
    

    }

2 Comments

POI 2.5.1? The current stable version of Apache POI (as of this writing) is 3.9.
Yes that's true, you can use the latest version which is 3.9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.