'How to create hyperlink of local file in excel using Java
I would like to insert a local file which was placed in my laptop in to Excel by creating a hyperlink using java. I have wrote the following code and the code was successfully executed with no errors, but when am trying to open the excel to see the hyperlink, only text was seen but no hyperlink was created on mouse hovering.
package practise;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
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() throws IOException {
// 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(HyperlinkType.FILE);
String url = "file:///C:%5CUsers%5CTest%5Ceclipse-workspace%5CTest%5COTest.mp3";
url = url.replaceAll(" ", "%20");
System.out.println("URL is : " + url);
link.setAddress(url);
cell.setHyperlink((XSSFHyperlink) link);
cell.setCellStyle(linkStyle);
// Writing the File
FileOutputStream output = new FileOutputStream(ck
new File("./Test.xls"));
// Writing the content
myWorkbook.write(output);
output.close();
}
public static void main(String[] args) throws Exception {
addLink();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
