2014-10-17 68 views
0

這是我的問題:如何將Excel文件中的單元格(字符串)值附加到JTextArea?

我嘗試從Excel文件中循環的單元格中追加值。我用這部分代碼:

Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile())); 
      Sheet sheet = workbook.getSheetAt(0); 

      for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) 
      { 
       Row row = rit.next(); 

       for(Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) 
       { 
        Cell cell = cit.next(); 


        cell.setCellType(Cell.CELL_TYPE_STRING); 

        while(cit.hasNext()) 
        { 
         notatnik.append(String.valueOf(cell.getSheet().toString()) + "\n"); 
        } 

       System.out.print(cell.getStringCellValue() + "\t");   
       } 
       System.out.println(); 
      } 

但它只是回來值「1」或「[email protected]」。在Excel中我舉例如下: 1 SP25 kp 5 6.5等

我該怎麼辦,從Excel中取回這個值到JTextArea?

PS。我使用POI 3.10庫。

回答

0

您正在使用迭代器有點亂......

迭代器應採用這種方式:

Iterator<Cell> cit = row.cellIterator(); // you get the iterator ... 

while (cit.hasNext()) { 
    // let't go cell by cell 
    Cell cell = cit.next(); 
    System.out.println(cell.getStringCellValue()); 
} 

不知道你爲什麼要打印出cell.getSheet()因爲該值始終是相同(你在同一張紙上)...可能你正在尋找cell.getValue() ...或類似的東西

+0

謝謝,我試了一下。 Noo我只使用「System.print.put(...)」檢查此方法是否工作:) – 2014-10-17 18:01:49

0

如果有人正在尋找答案(和我有同樣的問題),這是代碼的一部分從我的程序:

JFileChooser fileChooser = new JFileChooser(); 

     if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) 
     { 
      try 
      { 
       Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile())); 
       Sheet sheet = workbook.getSheetAt(0); 

       for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) 
       { 
        Row row = rit.next(); 

        for(Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) 
        { 
         Cell cell = cit.next(); 

         cell.setCellType(Cell.CELL_TYPE_STRING); 
         notatnik.append(cell.getStringCellValue() + "\t"); 
        } 
        notatnik.append("\n"); 
       } 
      } 
      catch (FileNotFoundException e1) 
      { 
       e1.printStackTrace(); 
      } 
      catch (IOException e2) 
      { 
       e2.printStackTrace(); 
      } 
     } 

這部分代碼從excel文件中獲取所有值並將它們粘貼到JTextArea中,名爲「notatnik」。

相關問題