2016-05-06 55 views
1

我正在使用Apache POI讀取Excel文件。 我的Excel表格的結構是這樣的在單列中讀取包含多個值的Excel文件-Java

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

所以右側的數據,我需要它分配給2000

到現在我已經實現了這種方式:

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

當我編譯時,它會在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得到1山坳的價值。(2000) 和使用oldName得到令牌的基礎上「」 delimiter-在這案例2001年,2003年,2008年,2009年

使用oldName所有這些值,了newName 2000年將被映射。

UPDATE:原因我正在'空指針異常'那裏,因爲一些細胞以第二柱(nextRow.getCell(1))爲空。

所以無論何時迭代器到達空單元格,它都會拋出空指針異常。 這裏需要

通過

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

分配缺少格策(它只是把空白空值)

這種方式,您也可以解決空指針異常在Excel而從空值讀取

相關問題