使用XSSFWorkbook Sheet接口会导致Java Null指针异常

时间:2014-02-20 20:13:55

标签: java excel xssf

我正在尝试使用org.apache.poi.ss.usermodel中的XSSFWorkbook来读取Excel文件。出于某种原因,当我尝试从其中一个Sheet方法中提取数据时,我得到一个Null Pointer异常。我是Java编程的新手,它可能是非常基础的东西。

import org.apache.poi.ss.usermodel.*;
public class ReadFile {

public static void main(String[] args) throws InterruptedException, IOException {

    File f = new File("C:/Users/munish/Documents/Training/Selenium/sample.xlsx");
    FileInputStream file = new FileInputStream(f);
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    Sheet sheet = workbook.getSheetAt(0);

    int rowsCount = sheet.getPhysicalNumberOfRows();
    System.out.println("Total number of rows: " + (rowsCount + 1));
    for (int i = 0; i <= rowsCount; i++) {
        Row row = sheet.getRow(i);
        int colCounts = row.getPhysicalNumberOfCells();
        System.out.println("Total number of Cols: " + colCounts);
        for (int j = 0; j < colCounts; j++) {
            Cell cell = row.getCell(j);
            System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
        }
    }

1 个答案:

答案 0 :(得分:-2)

您的for循环应为:

for (int i = 0; i < rowsCount; i++)

for (int i = 0; i <= rowsCount; i++)