使用Apache POI API从Excel文件中读取值

时间:2014-01-26 07:35:16

标签: java apache-poi

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

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

}

1 个答案:

答案 0 :(得分:3)

一旦遇到单个特定的单元格值,就会立即退出,因此您始终会始终获得相同的结果。

要彻底遍历工作表,在迭代rows时,您必须处理该行中单元格的Iterator。获得单个Cell实例的句柄后,将其值存储为Java Collection而不是仅存储1个值。

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