2016-05-06 4 views
1

Apache POIを使用してExcelファイルを読み込んでいます。複数の値を含むExcelファイルを単一の列に読み込みます。-Java

List<Class> list = new ArrayList<Class>(); 
     File file = new File(file_path); 
     FileInputStream fis = new FileInputStream(file); 

     //Create an instance of workbook which refers to an excel file 
     XSSFWorkbook wb = new XSSFWorkbook(fis); 

     //This selects the 1st sheet 
     XSSFSheet sheet = wb.getSheetAt(0); 

     //Iterate through each row one by one 
     Iterator<Row> itr = sheet.iterator(); 
     String newName = null; 
     String oldName = null; 


     while(itr.hasNext()){ 
      Row nextRow = itr.next(); 
      // For each row, iterate through all the columns 
      Iterator<Cell> cellIterator = nextRow.cellIterator(); 
      while (cellIterator.hasNext()) 
      { 
       Cell cell = cellIterator.next(); 

       newName = nextRow.getCell(0).toString(); 

       if(nextRow.getCell(1).toString().contains(",")){ 
        StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),","); 
        while(st.hasMoreTokens()){ 
         oldName = st.nextToken(); 
        } 
       } 
       else{ 
        oldName = nextRow.getCell(1).toString(); 
       } 
      } 

      System.out.println(); 
     } 

: 私のExcelのテーブル構造は、右側のデータのために、私は今、私はこの方法を実装しましたティル2000年代

に割り当てることが必要ですので、この

|2000s| 2001, 2003, 2008, 2009| 

のようなものですコンパイルすると、ヌルポインタの例外がnextRow.getCell(1)行にスローされます。

どのようにすべてのカンマ値を2000年にマップするのか分かりません。

これは、通常のデータ(コンマなし)では問題なく動作しています。

答えて

0

コンマ値は、誰かがここから助けを得ることができますので、私は答えを投稿してい

を扱ってきました。

String Tokenizerクラスが追加されました。セルにカンマがある場合、コンマ区切り文字で値が分割されます。

while(itr.hasNext()){ 
      Row nextRow = itr.next(); 
      // For each row, iterate through all the columns 
      Iterator<Cell> cellIterator = nextRow.cellIterator(); 
      while (cellIterator.hasNext()) 
      { 
       Cell cell = cellIterator.next(); 

       newName = nextRow.getCell(0).toString(); 

       if(nextRow.getCell(1).toString().contains(",")){ 
        StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),","); 
        while(st.hasMoreTokens()){ 
         oldName = st.nextToken(); 
        } 
       } 
       else{ 
        oldName = nextRow.getCell(1).toString(); 
        } 
      } 
      System.out.println(); 
     } 

以下のコードを見てましょう。ここNEWNAMEは、第一COLの値を取得します。(2000年代) とOLDNAMEこの中 '' delimiter-に基づいてトークンを取得しますOLDNAMEのすべてのこれらの値の場合2001、2003、2008、2009

NEWNAME 2000年代には、マッピングされます。

UPDATE:2列目(nextRow.getCell(1))でのいくつかのセルがNULLであるので、私は、そこ'NULLポインタ例外'を得ていた理由。

イテレータがヌルセルに到達するたびに、ヌルポインタ例外をスローします。 ここでは、

(それはちょうど空白としてNULL値を扱います)

Cell cell2 = row.getCell(j,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK); 

によって欠落セル方針

を割り当てるためには、Excel中でも解決nullポインタ例外ことができます。この方法が必要ですヌル値から読み取る

関連する問題