Skip to main content

How to Add, Read, Update, and Remove Hyperlinks in Excel with Java

 Excel workbooks often contain more than numbers and formulas. A supplier list, for example, might link to product pages, technical documentation, or a purchasing contact's email address. Those links make the spreadsheet useful, but maintaining them can become a chore when websites move or dozens of records need updating.

With Java, you can manage hyperlinks directly in an Excel workbook. This tutorial shows how to add hyperlinks to Excel cells, read existing links, update their destinations, and remove links without deleting the displayed text.

How to Add, Read, Update, and Remove Hyperlinks in Excel with Java

Set Up the Java Project

Add the following repository and dependency to your Maven project's pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>16.3.1</version>
    </dependency>
</dependencies>

If these sections already exist in your pom.xml, add the new entries inside them rather than creating duplicate sections.

1. Add Website and Email Hyperlinks to Excel

Suppose you're building a supplier directory with links to each supplier's website and a purchasing contact's email address. Instead of putting long URLs directly in the cells, you can display short, descriptive text and attach a hyperlink to it.

Use Worksheet.getHyperLinks().add() to create a hyperlink for a cell. Then set its type with setType(), its visible text with setTextToDisplay(), and its destination with setAddress(). Website links use HyperLinkType.Url; an email link can use the same type with a mailto: address.

Complete Java code:

import com.spire.xls.*;

public class AddExcelHyperlinks {

    public static void main(String[] args) {
        Workbook workbook = new Workbook();

        try {
            Worksheet sheet = workbook.getWorksheets().get(0);
            sheet.setName("Supplier Directory");

            // Add column headers
            sheet.getRange().get("A1").setText("Contact");
            sheet.getRange().get("B1").setText("Link");

            // Add a website hyperlink for Supplier A
            sheet.getRange().get("A2").setText("Supplier A");
            HyperLink link1 = sheet.getHyperLinks().add(sheet.getRange().get("B2"));
            link1.setType(HyperLinkType.Url);
            link1.setTextToDisplay("Visit Supplier A website");
            link1.setAddress("https://example.com/supplier-a/old");

            // Add a website hyperlink for Supplier B
            sheet.getRange().get("A3").setText("Supplier B");
            HyperLink link2 = sheet.getHyperLinks().add(sheet.getRange().get("B3"));
            link2.setType(HyperLinkType.Url);
            link2.setTextToDisplay("Visit Supplier B website");
            link2.setAddress("https://example.com/supplier-b");

            // Add an email hyperlink
            sheet.getRange().get("A4").setText("Purchasing Contact");
            HyperLink emailLink = sheet.getHyperLinks().add(sheet.getRange().get("B4"));
            emailLink.setType(HyperLinkType.Url);
            emailLink.setTextToDisplay("Send an email");
            emailLink.setAddress("mailto:procurement@example.com");

            sheet.getRange().get("A:A").setColumnWidth(22);
            sheet.getRange().get("B:B").setColumnWidth(30);

            workbook.saveToFile("supplier_directory.xlsx", ExcelVersion.Version2016);
        } finally {
            workbook.dispose();
        }
    }
}

The program creates supplier_directory.xlsx with two website links and one email link. The example.com URLs are placeholders; replace them with real destinations in your own project. An email link opens the user's configured email application, if one is available.

2. Read Hyperlinks from an Excel Worksheet

If you receive a workbook containing many links, you may need to audit their destinations before updating the file. Reading the cell's text alone isn't enough: a cell might display “Visit Supplier A website” while pointing to a much longer URL.

Worksheet.getHyperLinks() returns the worksheet's hyperlink collection. You can loop through it and retrieve each link's cell location, displayed text, and target address using getRange(), getTextToDisplay(), and getAddress().

The next example reads the workbook created above.

Complete Java code:

import com.spire.xls.*;
import com.spire.xls.collections.HyperLinksCollection;

public class ReadExcelHyperlinks {

    public static void main(String[] args) {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("supplier_directory.xlsx");
            Worksheet sheet = workbook.getWorksheets().get(0);
            HyperLinksCollection links = sheet.getHyperLinks();

            for (int i = 0; i < links.getCount(); i++) {
                int row = links.get(i).getRange().getRow();
                int column = links.get(i).getRange().getColumn();
                String displayText = links.get(i).getTextToDisplay();
                String address = links.get(i).getAddress();

                System.out.println("Cell: row " + row + ", column " + column);
                System.out.println("Display text: " + displayText);
                System.out.println("Address: " + address);
                System.out.println("--------------------");
            }
        } finally {
            workbook.dispose();
        }
    }
}

This prints the location and destination of each hyperlink in the selected worksheet. It reads the saved addresses; it does not check whether the websites are reachable. If your workbook contains links on several worksheets, repeat the same process for each sheet.

3. Update an Existing Excel Hyperlink

A supplier may move its product pages to a new URL, while the rest of the supplier record stays the same. Rather than deleting the cell and creating another link, you can update the existing hyperlink's destination with setAddress() and, if necessary, change its displayed text with setTextToDisplay().

The example below finds the hyperlink associated with cell B2. Checking its cell location is safer than assuming it will always be the first item in the collection.

Complete Java code:

import com.spire.xls.*;
import com.spire.xls.collections.HyperLinksCollection;

public class UpdateExcelHyperlink {

    public static void main(String[] args) {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("supplier_directory.xlsx");
            Worksheet sheet = workbook.getWorksheets().get(0);
            HyperLinksCollection links = sheet.getHyperLinks();

            for (int i = 0; i < links.getCount(); i++) {
                int row = links.get(i).getRange().getRow();
                int column = links.get(i).getRange().getColumn();

                if (row == 2 && column == 2) { // Cell B2
                    links.get(i).setAddress("https://example.com/supplier-a/new");
                    links.get(i).setTextToDisplay("Visit Supplier A's new website");
                    break;
                }
            }

            workbook.saveToFile("supplier_directory_updated.xlsx",
                    ExcelVersion.Version2016);
        } finally {
            workbook.dispose();
        }
    }
}

The new workbook contains the updated link in B2, while the other hyperlinks remain unchanged. For larger updates, you can inspect each saved address and replace matching URL patterns, such as an old domain name.

4. Remove an Excel Hyperlink Without Deleting Its Text

Sometimes a link is no longer needed, but the label in the cell is still useful. For example, Supplier B's website may have been retired, yet you still want to keep “Visit Supplier B website” in your directory for reference.

Use HyperLinksCollection.removeAt() to remove the hyperlink from the collection. This removes the link itself without clearing the cell's displayed text. The following code finds the hyperlink in B3 and removes it.

Complete Java code:

import com.spire.xls.*;
import com.spire.xls.collections.HyperLinksCollection;

public class RemoveExcelHyperlink {

    public static void main(String[] args) {
        Workbook workbook = new Workbook();

        try {
            workbook.loadFromFile("supplier_directory.xlsx");
            Worksheet sheet = workbook.getWorksheets().get(0);
            HyperLinksCollection links = sheet.getHyperLinks();

            // Iterate backward so removals do not shift unchecked indexes
            for (int i = links.getCount() - 1; i >= 0; i--) {
                int row = links.get(i).getRange().getRow();
                int column = links.get(i).getRange().getColumn();

                if (row == 3 && column == 2) { // Cell B3
                    links.removeAt(i);
                }
            }

            workbook.saveToFile("supplier_directory_without_link.xlsx",
                    ExcelVersion.Version2016);
        } finally {
            workbook.dispose();
        }
    }
}

The text in B3 remains, but its hyperlink is removed. If you need to remove every regular cell hyperlink in the worksheet, iterate backward through the entire collection and call removeAt(i) for each one. Note that the cell may still retain blue text or underlining from its previous hyperlink formatting.

Common Questions

Why does the cell show a label instead of the URL?

Excel stores a hyperlink's display text separately from its destination. A cell can show “Visit Supplier A website” while linking to https://example.com/supplier-a. Use getAddress() to retrieve the destination instead of relying on the displayed cell value.

Why is the text still blue and underlined after I remove a hyperlink?

Removing a hyperlink does not necessarily reset the cell's existing formatting. If the text still looks like a link, adjust the font color and underline settings separately.

Does this code also find links created with the HYPERLINK formula?

Not necessarily. A formula such as =HYPERLINK("https://example.com", "Visit website") is stored as a cell formula and may not appear in Worksheet.getHyperLinks(). To process those links, examine the cell formulas separately.

Can Java check whether an Excel hyperlink is broken?

You can extract the URL with getAddress() and then check it using an HTTP client. However, a failed request doesn't always mean the URL is invalid: access controls, redirects, network issues, and automated-request blocking can affect the result.

Can I link to another sheet in the same workbook?

Yes. Excel supports internal workbook hyperlinks. When creating one, use HyperLinkType.Workbook and specify a valid location in the workbook rather than a website URL. Make sure the destination sheet and cell reference exist.

Conclusion

Managing Excel hyperlinks programmatically is useful when a workbook contains many supplier websites, document references, or contact addresses. You can add new links, inspect existing destinations, update outdated URLs, or remove hyperlinks while keeping the cell text intact.

The important distinction is between a hyperlink's display text and its target address. Once you handle them separately, maintaining links in larger Excel files becomes much easier.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...