Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents.
Installation:
There are two ways to install the Apache POI dependency in our java project:
- Download below mentioned Jar files from poi.apache.org/download.html:
- Maven Dependency: Set the following dependency in the maven project as:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>
Environment Setup:
- Make a project Using java maven.
- Go to poi.apache.org/download.html and add the dependency into your project. By this, the libraries get imported into your project.
- Now, make a java class under com.mycompany.<Your Project Name> in Source Packages.
- Nice, now you can use the libraries.
Approach:
- Create a workbook.
- Create a spreadsheet in workbook.
- Create a cell and add color, content and styling to it.
- Add the address and apply the link colors to it.
- Add cell in spreadsheet.
- Repeat step 3 to 5 to write more data
Below is the implementation of the above approach:
Java
// How to add hyperlink to the // contents of a cell using Java? import java.io.File; import java.io.FileOutputStream; import org.apache.poi.common.usermodel.Hyperlink; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFHyperlink; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class HyperLink { public static void addLink() { // Create a Workbook XSSFWorkbook myWorkbook = new XSSFWorkbook(); // Create a Spread Sheet XSSFSheet newSpreadsheet = myWorkbook.createSheet( "Custom Links" ); XSSFCell cell; // Create Helpers CreationHelper helper = myWorkbook.getCreationHelper(); XSSFCellStyle linkStyle = myWorkbook.createCellStyle(); XSSFFont linkFont = myWorkbook.createFont(); // Setting the Link Style linkFont.setUnderline(XSSFFont.U_SINGLE); linkFont.setColor(HSSFColor.BLUE.index); linkStyle.setFont(linkFont); // Adding a Link cell = newSpreadsheet.createRow( 1 ).createCell( ( short ) 2 ); cell.setCellValue( "Link" ); XSSFHyperlink link = (XSSFHyperlink)helper.createHyperlink( Hyperlink.LINK_URL); cell.setHyperlink((XSSFHyperlink)link); cell.setCellStyle(linkStyle); // Writing the File FileOutputStream output = new FileOutputStream( new File( "C:/HyperLink.xlsx" )); // Writing the content myWorkbook.write(output); output.close(); } public static void main(String[] args) throws Exception { addLink(); } } |
Output: