2013-06-15 5 views
0

특정 열의 셀 값을 기준으로 행을 가져와야하는 excel 시트가 있습니다. 예를 들어 cityemployee _name이라는 열이 있습니다. 내 Java 코드를 사용하여 city 값을 제공 할 것이고 지정된 열의 값이 city 인 모든 행을 반입해야합니다. 열 이름이 고정됩니다. 내 자바 코드에서 라스베가스로 셀 값을 주면단일 셀 값을 기준으로 전체 Excel 행 가져 오기

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

그래서, 1, 2 & 3.

+0

나는 Aapche POI에 초보자이며 배우려 고합니다. 나는 세포 독서와 세포 생성과 같은 작은 프로그램을 개발했다. 어제부터 내가 도움을받을 수 있다면 도움이 될 것입니다. –

+1

시도한 코드를 공유하십시오. –

+0

apache-poi를 사용하면 도시가 발견되면 도시를 반복 검사하고 확인해야합니다. 그러면 다른 목록에 값을 추가하십시오. –

답변

1
  1. 통해 UR 프로젝트 poi-의 lib 폴더에 넣고 나에게 행을 인출해야하므로 2.5.1.jar
  2. 보십시오 다른 u는 단순히/피 메소드 인수
  3. 무효 uploadBulkQuestions (ExcelUploadForm excelUploadForm, 문자열적인 filePath에서 HttpSession이 매개 변수를 삭제하는 간단한 클래스에서 사용할 수 있습니다 스트럿 작업에이 방법을 사용하려면, HttpSession이 sessi on) SQLException을 던졌습니다 // 매개 변수에서 ExcelUploadForm obj를 무시할 수 있습니다 { ExcelForm excelForm = null; /** * // ExcelForm은 setter 및 getter가있는 간단한 pojo입니다. * * public class ExcelForm은 ActionForm { * String city; * 문자열 employeeName; * 정수 연령; * // 위 변수의 setter 및 getters. *} */ 짧은 CityPosition = 0; short Employee_NamePosition = 1; 짧은 AgePosition = 2; 연결 con = null; ArrayList invalidFields = new ArrayList(); ArrayList validFields = new ArrayList(); 부울 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

POI 2.5.1? Apache POI의 현재 안정 버전 (이 글을 쓰는 시점에서)은 3.9입니다. – rgettman

+0

네, 맞습니다. 최신 버전 인 3.9를 사용할 수 있습니다. –

0

당신은 방법에 따라 사용할 수 있습니다. "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; 
} 
관련 문제