本章说明如何向单元格中的内容添加超链接。通常,超链接用于访问任何Web URL,电子邮件或外部文件。

    以下代码显示了如何在单元格上创建超链接。

    1. import java.io.File;
    2. import java.io.FileOutputStream;
    3.  
    4. import org.apache.poi.common.usermodel.Hyperlink;
    5. import org.apache.poi.hssf.util.HSSFColor;
    6. import org.apache.poi.ss.usermodel.CreationHelper;
    7. import org.apache.poi.xssf.usermodel.XSSFCell;
    8. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
    9. import org.apache.poi.xssf.usermodel.XSSFFont;
    10. import org.apache.poi.xssf.usermodel.XSSFHyperlink;
    11. import org.apache.poi.xssf.usermodel.XSSFSheet;
    12. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    13.  
    14. public class HyperlinkEX {
    15. public static void main(String[] args) throws Exception {
    16. XSSFWorkbook workbook = new XSSFWorkbook();
    17. XSSFSheet spreadsheet = workbook.createSheet("Hyperlinks");
    18. XSSFCell cell;
    19. CreationHelper createHelper = workbook.getCreationHelper();
    20. XSSFCellStyle hlinkstyle = workbook.createCellStyle();
    21. XSSFFont hlinkfont = workbook.createFont();
    22. hlinkfont.setUnderline(XSSFFont.U_SINGLE);
    23. hlinkfont.setColor(HSSFColor.BLUE.index);
    24. hlinkstyle.setFont(hlinkfont);
    25.  
    26. //URL Link
    27. cell = spreadsheet.createRow(1).createCell((short) 1);
    28. cell.setCellValue("URL Link");
    29. XSSFHyperlink link = (XSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_URL);
    30. link.setAddress("http://www.tutorialspoint.com/");
    31. cell.setHyperlink((XSSFHyperlink) link);
    32. cell.setCellStyle(hlinkstyle);
    33.  
    34. //Hyperlink to a file in the current directory
    35. cell = spreadsheet.createRow(2).createCell((short) 1);
    36. cell.setCellValue("File Link");
    37. link = (XSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_FILE);
    38. link.setAddress("cellstyle.xlsx");
    39. cell.setHyperlink(link);
    40. cell.setCellStyle(hlinkstyle);
    41.  
    42. //e-mail link
    43. cell = spreadsheet.createRow(3).createCell((short) 1);
    44. cell.setCellValue("Email Link");
    45. link = (XSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_EMAIL);
    46. link.setAddress("mailto:contact@tutorialspoint.com?" + "subject = Hyperlink");
    47. cell.setHyperlink(link);
    48. cell.setCellStyle(hlinkstyle);
    49.  
    50. FileOutputStream out = new FileOutputStream(new File("hyperlink.xlsx"));
    51. workbook.write(out);
    52. out.close();
    53. System.out.println("hyperlink.xlsx written successfully");
    54. }
    55. }

    将上面的代码另存为HyperlinkEX.java。如下从命令提示符编译并执行它。

    1. $javac HyperlinkEX.java
    2. $java HyperlinkEX

    它将在当前目录中生成一个名为hyperlink.xlsx的Excel文件,并在命令提示符下显示以下输出。

    1. hyperlink.xlsx written successfully

    The hyperlink.xlsx file looks as follows.

    hyperlink.jpeg