根据单个单元格值获取整个Excel行

时间:2013-06-15 05:40:06

标签: java apache-poi

我有一张excel工作表,我需要根据特定列的单元格值来获取行。例如,我有一个名为cityemployee _ name的列。我将使用我的Java代码提供city值,它应该获取指定列中具有city值的所有行。列名将被修复。

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

所以,如果我从我的Java代码中将单元格值作为Vegas赋予它,那么它应该取给我1,2和1行。 3.

2 个答案:

答案 0 :(得分:1)

  1. 把它放在你的项目poi-2.5.1.jar
  2. 的lib文件夹中
  3. 尝试在struts中使用此方法Action其他你可以简单地在简单类中使用它来避免/删除方法参数中的HttpSession参数
  4. void uploadBulkQuestions(ExcelUploadForm excelUploadForm,String filePath,HttpSession session)抛出SQLException //你可以忽略参数中的ExcelUploadForm obj {     ExcelForm excelForm = null;     / **     * //这里ExcelForm是一个带有setter和getter的简单pojo     *     * public class ExcelForm扩展ActionForm {     *弦城;     * String employeeName;     *整数年龄;     * //以上变量的setter和getter。     *}     * /     short CityPosition = 0;     short Employee_NamePosition = 1;     短AgePosition = 2;     连接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;
    

    }

答案 1 :(得分:1)

您可以使用以下方法。 “sheet”是您需要执行搜索的工作表, “colName”是列的名称,根据您的要求,它将被修复。 和“textToFind”是你必须在colName列中找到的文本。

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;
}