2015-06-06 23 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

謝謝,但這不工作對不起 –

相關問題