有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

线程“main”java中出现错误异常。带有的lang.NullPointerException。xlsx文件

我有一张表格,它包括:号码、姓名、通行证、通行证、结果。我想要获取testweb的名称、传递、结果,我尝试编写它,但出现以下错误:

String user[],pass[],result[];
Workbook workbook = WorkbookFactory.create(new File(pathFile));
Sheet sheet = workbook.getSheetAt(0);
workbook.close();
if (sheet != null) {
int rowindex =0;
for(Row row : sheet) {
   for(Cell cell:row){
      int i=cell.getColumnIndex();
      if(i==1) user[rowindex]=cell.toString();
      if(i==2) pass[rowindex]=cell.toString();
      if(i==4) result[rowindex]=cell.toString();
      }
      rowindex++;
  }
} else {
    System.out.println("Sheet was not found");
  }    

共 (2) 个答案

  1. # 1 楼答案

    它起作用了

       if (sheet != null) {  
              rowNum=sheet.getLastRowNum()+1; //getlastrow() return index last row
              String username[]=new String[rowNum];
              int index=0;
              Iterator<Row> rowIterator = sheet.iterator();
                    while (rowIterator.hasNext()) {
                            Row row = rowIterator.next();
                            Iterator <Cell> cellIterator = row.cellIterator();
                            index++;
                               while (cellIterator.hasNext()) {
                                   Cell cell = cellIterator.next();
                                   if(cell.getColumnIndex()==1) 
                                   username[index]=cell.toString();
                                }
                       }
    
         } else {
            System.out.println(" Sheet was not found ");
         }
    
  2. # 2 楼答案

    在你的问题中没有太多的细节,但根据你的代码,我猜你会这样做

     FileInputStream inputStream = new FileInputStream(new File(file));
     Workbook workbook = new XSSFWorkbook(inputStream);
     Sheet sheet = workbook.getSheetAt(0);
    

    我猜你的工作表是空的。因此,您需要在检查中输入一些保护代码,以确保您拥有有效的工作表

    像这样的

     if (sheet != null) {
        int n = sheet.getLastRowNum();
        // Do the rest of you code
    } else {
        System.out.println("Sheet was not found Check to make sure file was read and sheet was access properly.");
    }