2016-07-28 159 views
0

我想從我的Excel電子表格中閱讀超鏈接單元格,但我無法這樣做。當我進入電子表格並刪除超鏈接時,它讀取得很好。我在下面的另一個問題(How to get hyperlink address from a cell in excel by using java?)中遇到了一個解決方案,但getHyperlink方法只適用於工作表,而不是使單元格困惑我。JXL閱讀使用Java的Excel中的超鏈接單元格

Workbook wb = WorkbookFactory.create(new File("test.xls")); 
Sheet s = wb.getSheetAt(0); 
Row r2 = s.getRow(1); // Rows in POI are 0 based 
Cell cB2 = r2.getCell(1); // Cells are 0 based 

Hyperlink h = cB2.getHyperlink(); 
if (h == null) { 
    System.err.println("Cell B2 didn't have a hyperlink!"); 
} else { 
    System.out.println("B2 : " + h.getLabel() + " -> " + h.getAddress()); 
} 

這是我的代碼剛纔

import jxl.Cell; 
import jxl.Sheet; 
import jxl.Workbook; 
import jxl.read.biff.BiffException; 

public String[] readUsernameFromExcel() { 
     File src = new File("C:/filepath.xls"); 
     String ex[] = new String[10]; 

     try { 

      Workbook wb = Workbook.getWorkbook(src); 
      Sheet sh1 = wb.getSheet(0); 

      Cell a3 = sh1.getCell(0, 2); 
      Cell b3 = sh1.getCell(1,2); 


      Cell c2 = sh1.getCell(2,1); //this is the cell I want to read the hyperlink from 

      ex[0] = a3.getContents().trim(); 
      ex[1] = b3.getContents().trim(); 
      ex[2] = c2.getContents().trim(); 

      System.out.println(ex[0]); 
      System.out.println(ex[1]); 
      System.out.println(ex[2]); 

所以我試圖做的是

Hyperlink h = c2.getHyperlink(); 

但我與細胞使用時getHyperlink不起作用。

enter image description here

並且我不具有選項來添加getHyperlink()方法

enter image description here

但是當我使用的紙張它確實出現,儘管顯示爲超鏈接和是一個數組。

enter image description here

我感覺好像我是如此接近,但我不能想出什麼我丟失或做錯了所以任何幫助,讓我在鏈接上是極大的讚賞,在此先感謝!

+0

我剛剛實現了這一問題的答案是使用Apache POI和JXL不XSSF。所以我想問題是,我如何在JXL中做到這一點? – OhAye

回答

0

我只是決定使用Apache POI而不是getHyperlink方法。它就像一個魅力。我在下面發佈了我的代碼,希望有人發現它有用,如果他們發現自己在嘗試從JXL更改爲Apache POI時處於相同的情況!此外,如果你正在使用.xslx那麼你需要使用的,而不是HSSF(http://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi

public String[] readUsernameFromExcel() { 
     String ex[] = new String[10]; 
     try { 

      FileInputStream fileInputStream = new FileInputStream("filepath.xls"); 
      HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); 
      HSSFSheet worksheet = workbook.getSheetAt(0); 
      HSSFRow row1 = worksheet.getRow(2); 
      HSSFCell cellA3 = row1.getCell(0); 
      ex[0] = String.valueOf(cellA3.getNumericCellValue()).trim(); 

      HSSFRow row2 = worksheet.getRow(2); 
      HSSFCell cellB3 = row2.getCell(1); 
      ex[1] = cellB3.getStringCellValue(); 

      HSSFRow row3 = worksheet.getRow(1); 

      HSSFCell cellC2 = row3.getCell(2); 
      Hyperlink h = cellC2.getHyperlink(); 
      ex[2] = h.getAddress(); 

      System.out.println("A3: " + ex[0]); 
      System.out.println("B3: " + ex[1]); 
      System.out.println("C2: " + ex[2]); 

     }catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     }catch (IOException e) { 
      e.printStackTrace();} 


return ex; 

    }