簡體   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