2014-01-26 180 views
0

我正在使用程序从excel文件读取值,然后返回读取值。我曾尝试使用迭代器以及for循环,但程序不会返回工作表中的所有值。请建议。使用Apache POI API从Excel文件读取值

import java.io.FileInputStream; 
import java.util.ArrayList; 
import java.util.Iterator; 
import org.apache.poi.ss.usermodel.Row; 
    import org.apache.poi.ss.usermodel.Cell; 
    import org.apache.poi.ss.usermodel.CellValue; 
    import java.io.File; 

    import org.apache.poi.xssf.usermodel.XSSFSheet; 
    import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

    public class ExcelReading { 

public static STring ReadExcel(String Path){ 
    String FakeReturn = null; 
try 
    { 
     FileInputStream file = new FileInputStream(new File(Path)); 

     XSSFWorkbook workbook = new XSSFWorkbook(file); 

     XSSFSheet sheet = workbook.getSheetAt(0); 

     for(Row row:sheet) 
     { 
      Cell cell=row.getCell(0); 
      Cell testcell = row.getCell(1); 
      if(cell.getStringCellValue()!=null) 
      return testcell.getStringCellValue(); 
      else 
       break; 

     } 
     file.close(); 

    } 
    catch (Exception e) 
    { 
     System.out.println("The code carries an exception"); 
     e.printStackTrace(); 
     return FakeReturn; 
    } 

return FakeReturn; 
} 

}

+3

你真的认为这个代码将工作。 –

回答

3

退出,只要你遇到一个特定的单元格的值,因此你总是会得到一个相同的结果,所有的时间。

为了详细遍历工作表,在迭代rows时,必须获取该行内单元格的Iterator的句柄。一旦你得到一个单一的Cell实例的句柄,将它的值存储到一个Java Collection而不是只有一个单一的值。

Iterator<Row> rowIterator = sheet.iterator(); 

while (rowIterator.hasNext()) { 
    Row row = rowIterator.next(); 

    Iterator<Cell> cellIterator = row.cellIterator(); 
    while (cellIterator.hasNext()) { 
     Cell cell = cellIterator.next(); 
      cell.getStringCellValue(); //Do something useful with me 
... 

编辑: 要获得一个特定的列,使用CellReference,如下所示:

XSSFSheet ws = wb.getSheet("Sheet1"); 
CellReference cellReference = new CellReference("A11"); 
XSSFRow row = sheet.getRow(cellReference.getRow()); 
if (row != null) { 
    XSSFCell cell = row.getCell(cellReference.getCol()); 
} 
+0

有什么方法可以读取电子表格中特定列的值? – IntrepidBlue

+0

@ user2911856看看编辑,你可以用CellReference来获得一个特定列的句柄 – PopoFibo

+0

非常感谢!这就像一个魅力。 – IntrepidBlue

相关问题