繁体   English   中英

Apache POI获取NPE读取xls文件

[英]Apache POI gets NPE reading xls file

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

A栏|产品编号|已售出数量
................. | 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();

            }
}

但我得到了nullpointexceptions。

线程“main”java.lang.NullPointerException中的异常
在Read.readXLSFile(Read.java:29)
在Read.main(Read.java:45)
Java结果:1

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

更改

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

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

摆脱错误。 同样防御性编程(即检查null getCell(…)结果是一个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM