我正在尝试将XLS文件读入Java,看起来像这样
列A |产品ID |销售数量
................. | 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。
Read.main(Read.java:45)
处Read.readXLSFile(Read.java:29)处的线程“ main”中的java.lang.NullPointerException异常
Java结果:1
您遇到了一个错误:r
上升到numRows
,j
开始于r + 1
–在上一次迭代中为numRows + 1
。由于该行中没有内容,getCell(…)
因此将返回该行null
(按照API定义)。这是来自哪里NullPointerException
。
改变
for(int r=1;r<=numRows;r++){
到
for(int r=1;r<numRows;r++){
摆脱错误。防御性编程(即检查getCell(…)
结果)null
也是个好主意。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句