Apache POI 获取 NPE 读取 xls 文件

Apache POI gets NPE reading xls file

我正在尝试将 XLS 文件读入 java,它看起来像这样

Column A|Product ID|Number Sold
.................|105029 ....|15
.................|102930 ....|9
.................|203911 ....|29
.................|105029 ....|4

我需要将每个产品 ID 售出的产品总数相加,然后创建一个新文件,对数据进行排序。这个程序应该是灵活的,因为可能有 1000 个不同的产品 ID 或 400 个。下面的代码是我目前所拥有的......但是它有很多问题而且我缺少 java知识使它真的令人沮丧。

第一个 for 循环没有继续,它停留在 r=1,尽管第二个 for 循环继续。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Read {

            public static void readXLSFile() throws IOException{
           InputStream ExcelFile = new FileInputStream("C:/Sales Data.xls");
                HSSFWorkbook wb = new HSSFWorkbook(ExcelFile);
                HSSFSheet sheet=wb.getSheetAt(0);

                int numRows = sheet.getPhysicalNumberOfRows(); 
                //to intialize an array
                int[]idAccum = new int[numRows]; 
                //holds the product id
                int[]saleAccum = new int[numRows]; 
                //holds the total sales per product ID

                        for(int r=1;r<=numRows;r++){ 
                        //iterates through the product ID and matching sales
                            for(int j=r+1;j<numRows+1; j++){
                            HSSFCell rows = sheet.getRow(r).getCell(1);
                            HSSFCell cells = sheet.getRow(r).getCell(2);
                            HSSFCell rows1 = sheet.getRow(j).getCell(1);
                            HSSFCell cells1 = sheet.getRow(j).getCell(2);
                                if(rows==rows1){ 
                            //compares product ids
                                    idAccum[r]=rows1.getNumericCellValue(); 
                        //places product id in element r if rows and rows1 match
                                    saleAccum[r]+=cells.getNumericCellValue(); 
                        //adds number of items sold to corresponding product ID
                                }
                            }
                            System.out.println(idAccum[r]); 
                            System.out.println(saleAccum[r]);
                        }   
            }

            public static void main(String[] args) throws IOException {
        readXLSFile();

            }
}

但是我遇到了空点异常。

Exception in thread "main" java.lang.NullPointerException
at Read.readXLSFile(Read.java:29)
at Read.main(Read.java:45)
Java Result: 1

你有一个差一错误:r 上升到 numRowsjr + 1 开始——在最后一次迭代中是numRows + 1。由于该行中没有内容,因此 getCell(…) 将 return null (根据 API 定义)。这就是 NullPointerException 的来源。

改变

for(int r=1;r<=numRows;r++){

for(int r=1;r<numRows;r++){

消除错误。防御性编程(即检查 nullgetCell(…) 结果也是一个好主意。