如何使用Apache POI获取java中各行excel表的最后一列值

时间:2013-08-08 10:13:57

标签: java servlets apache-poi

我有以下excel表

id     JobId     Name      Dept        Add       Salary
101      41      Bob     Editing    New York     $ 5000 

我从$ .ajax()方法将id,jobid作为请求参数传递给servlet。我想通过匹配请求参数,即id和jobid与excel表内容,并将其插入其他表,获得excel表的工资单元数据。怎么做?

这是我的代码......

   FileInputStream file = new FileInputStream(fileToBeRead);
   workbook = new HSSFWorkbook(file);
   int jobid = Integer.ParseInt(request.getParameter("jobid"));

          if (id == 101) {
             // get first sheet 
               HSSFSheet sheet = workbook.getSheetAt(0);
               Iterator<Row> rowIterator = sheet.iterator();
               statement = conn.createStatement() ;
               ResultSet resultset = statement.executeQuery("Select job_id,Job,Name, Deptname from Emp,Department where Department.job_id=" + jobid + " AND Emp.Id=" + id + " ");

                while (resultset.next()) { 

                   //how to match database result with excel records and save to other table



                }//resultset.next() ends here...

            resultset.close();
        }
我尝试这样做......?例如,但它给出了错误 我试图匹配id = 101和Add =纽约,例如,想得到薪水数据。 如果使用 if(data [i] [j] .equalsIgnoreCase(“101”))条件它可以工作,但我想匹配id和地址,即 if(data [i] [j ] .equalsIgnoreCase(“101”)&amp;&amp; data [i] [j + 5] .equalsIgnoreCase(“New York”))它给出错误

    int rowNum = sheet.getLastRowNum() + 1;
    int colNum = sheet.getRow(0).getLastCellNum();
    String[][] data = new String[rowNum][colNum];
   // System.out.println("Row No :"+rowNum +" \nCol no:"+colNum);

    for (int i = 1; i < rowNum; i++) {
        Row row = sheet.getRow(i);
        for (int j = 0; j < colNum; j++) {
            Cell cell = row.getCell(j);
            String value = null;
            double price;
           // int type = cell.getCellType();

            value = cell.getStringCellValue();

                    data[i][j] = value;
                    if(data[i][j].equalsIgnoreCase("101") && data[i][j+4].equalsIgnoreCase("New York"))
                        {
                            Cell lastCellInRow = row.getCell(row.getLastCellNum() - 1);
                            System.out.println(lastCellInRow.getStringCellValue());

                    }

        }
    }

1 个答案:

答案 0 :(得分:2)

如果您只是尝试访问连续的最后一个单元格,并且您有Row,请尝试以下操作:

Cell lastCellInRow = row.getCell(row.getLastCellNum() - 1); // -1 because #s are 0-based

编辑要解决您的更新问题和以下评论。 这段代码应该可以满足您的需求,而无需经历将整个电子表格转换为2D数组的严格要求,当您可以轻松访问所有数据时,这非常低效。

for (int i = 1; i < rowNum; i++) {
  Row row = sheet.getRow(i);
  Cell cell1 = row.getCell(0);
  Cell cell2 = row.getCell(4);
  String id = cell1.getStringCellValue();
  String city = cell2.getStringCellValue();

  if(id.equalsIgnoreCase("101") && city.equalsIgnoreCase("New York")) {
    Cell lastCellInRow = row.getCell(row.getLastCellNum() - 1);
    System.out.println(lastCellInRow.getStringCellValue());
  }
}