0

我有以下excel表

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

我将 id,jobid 作为请求参数从 $.ajax() 方法传递给 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=New York,例如并想要获取工资数据。如果使用if(data[i][j].equalsIgnoreCase("101"))条件它可以工作,但我想同时匹配 id 和 Address 即if(data[i][j].equalsIgnoreCase("101") && 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());

                    }

        }
    }
4

1 回答 1

2

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

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

编辑解决您更新的问题和下面的评论。这段代码应该可以满足您的需求,而无需将整个电子表格转换为二维数组,坦率地说,当您可以轻松访问所有数据时,这种操作效率非常低。

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());
  }
}
于 2013-08-08T13:37:43.333 回答