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

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

}

最佳答案

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

要彻底遍历工作表,在迭代时,您必须获取该行内单元格的迭代器句柄。获得单个 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());
}

关于java - 使用 Apache POI API 从 Excel 文件读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21360950/

相关文章:

java - 使用 iText 和 PdfGraphics2D 的 PPTX 到 PDF 错误

java - 当我尝试关闭 MySQL 连接时出错

Java 不运行这个 for 循环

java - 如何使用 apache poi 设置 word 文档的页边距?

java - 是否可以使用 POI 更改现有 Excel 中的列分组?

java - APACHE POI 从 Java 中的 Excel 获取精确的字体颜色

java - 如何使用 JavaFX BarChart 在水平线上添加文本

java - 如何用基元替换 Integer 对象

java - 使用 Liferay 的 DynamicQuery 按另一个表排序

java.lang.ClassNotFoundException : org. apache.poi.xssf.usermodel.XSSFWorkbook