我正在尝试从Excel电子表格中读取超链接单元格,但我无法这样做。当我进入电子表格并删除超链接时,它就读得很好。我确实在另一个问题(How to get hyperlink address from a cell in excel by using java?)中遇到了下面的解决方案,但getHyperlink方法仅适用于工作表,而不适用于让我困惑的单元格。
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不起作用。
我没有选择添加getHyperlink()方法
但是当我使用它确实出现时,它虽然显示为超链接并且是一个数组。
我觉得我好像离我太近了但是我无法弄清楚我错过了什么或做错了所以非常感谢任何帮助让我通过这个链接,感谢提前!
答案 0 :(得分:0)
我决定使用Apache POI,而不是getHyperlink方法。它就像一个魅力。我已经在下面发布了我的代码,希望有人发现它有用,如果他们发现自己处于尝试从JXL更改为Apache POI的相同情况!此外,如果您使用.xslx,则需要使用XSSF而不是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;
}