2015-06-06 25 views
0

我在我的c:驱动器(本地计算机)中有一个名为abc.xls的excel文件,现在在第一个工作表本身的excel文件中有一张表,如下所示,如何在Excel工作表中找到表格数据

TradeRef TMS Deal  Date  B/S 
12   45 DRT 23/97/2014 RTY 
23   36 QWE 21/07/2015 WER 

现在请告诉如何通过Java中的apachae poi从Excel表读取此表。

现在问题是这张表可以在表格的任何范围内,例如,它可能以A1单元格开始,或者它可能以F25开始,所以换句话说,表格可以在任何范围在表单中。我担心的是要首先到达TradeRef所在范围的起始点,请告知如何到达那里,然后将内容打印到控制台中?

回答

2

Mi的第一条建议是与写入Excel文件的程序(或人)达成一致意见 - 或者至少要求人员打开工作表,然后用正确的参数调用程序,如

# F25 is the starting cell, 120 the number of rows 
java trade.App F25 120 

否则,你会留下的iterating在表的单元格的启发式方法和假设的出发点为第一单元,其文字内容是“TradeRef”(或类似检查所有你所期望的标题更复杂的变种)

public Cell findFirstRow(Sheet sheet) { 
    for (Row row : sheet) { 
    for (Cell cell : row) { 
     if (cell.getCellType() == Cell.CELL_TYPE_STRING 
      && "TradeRef".equals(cell.getStringCellValue() 
    ) { 
     int row = cell.getRowIndex() + 1; 
     int col = cell.getColumnIndex(); 
     if (sheet.getRow(row) == null) 
      throw new RuntimeException("Row " + row + 1 + " is empty!"); 
     Cell startOfFirstDataRow = sheet.getRow(row).getCell(col); 
     if (startOfFirstDataRow == null) { 
      CellReference ref = new CellReference(row, col); 
      throw new RuntimeException("Data not found at " + ref.formatAtString()); 
     } 
     return startOfFirstDataRow; 
     } 
    } 
    } 
    throw new RuntimeException("TradingRef header cell not found!"); 
} 
+0

非常感谢你能请告知我如何在Java中调用这个从主要方法,请你,请编辑代码,并显示请我们如何能够把这种从主方法在java本身 –

+0

这是你需要解决你的问题的所有代码。学习使用Java代码取决于您,无法在StackOverflow上执行此操作 – Raffaele

+0

获取无法从数字单元获取文本值的例外 –

0

也许这会为你工作:

try { 

     FileInputStream file = new FileInputStream(new File("C:\\test.xls")); 

     //Get the workbook instance for XLS file 
     HSSFWorkbook workbook = new HSSFWorkbook(file); 

     //Get first sheet from the workbook 
     HSSFSheet sheet = workbook.getSheetAt(0); 

     //Iterate through each rows from first sheet 
     Iterator<row> rowIterator = sheet.iterator(); 
     while(rowIterator.hasNext()) { 
      Row row = rowIterator.next(); 

      //For each row, iterate through each columns 
      Iterator<cell> cellIterator = row.cellIterator(); 
      while(cellIterator.hasNext()) { 

       Cell cell = cellIterator.next(); 

        if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { 

         switch(cell.getCellType()) { 
          case Cell.CELL_TYPE_BOOLEAN: 
           System.out.print(cell.getBooleanCellValue() + "\t\t"); 
           break; 
          case Cell.CELL_TYPE_NUMERIC: 
           System.out.print(cell.getNumericCellValue() + "\t\t"); 
           break; 
          case Cell.CELL_TYPE_STRING: 
           System.out.print(cell.getStringCellValue() + "\t\t"); 
           break; 
         } 
        } 
      } 
      System.out.println(""); 
     } 


    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally{ 
     file.close(); 
    } 
+0

谢谢,但这不工作对不起 –

相关问题