我正在尝试将 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
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
上升到 numRows
,而 j
开始于 r + 1
– 在最后一次迭代中是 numRows + 1
。由于该行中没有内容,因此 getCell(...)
将返回 vô giá trị
(根据 API 定义)。这就是 NullPointerException
的来源。
Thay đổi
for(int r=1;r<=numRows;r++){
đến
for(int r=1;r<>
消除错误。防御性编程(即检查 getCell(...)
结果是否为 vô giá trị
也是一个好主意。
Tôi là một lập trình viên xuất sắc, rất giỏi!