I'm trying to create an hyperlink to a file using APACHE POI XSSF using a relative path. When opening the .xlsx file created with Microsft Excel the relative path is modified and it is not well linked. Microsoft Excel adds some '../../' in front of the path. I try opening it with OpenOffice and it works OK. Also I tried it with HSSF and it works in both Microsoft Excel and OpenOffice. Any idea why is this happening? This is an example code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelHyperlinks {
public static void main(String[] args) throws Exception{
/* Create Workbook and Worksheet */
XSSFWorkbook my_workbook = new XSSFWorkbook();
XSSFSheet my_sheet = my_workbook.createSheet("Cell Hyperlink");
CreationHelper createHelper = my_workbook.getCreationHelper();
Hyperlink url_link=createHelper.createHyperlink(HSSFHyperlink.LINK_URL);
Hyperlink file_link=createHelper.createHyperlink(HSSFHyperlink.LINK_FILE);
Hyperlink email_link=createHelper.createHyperlink(HSSFHyperlink.LINK_EMAIL);
/* Define the data for these hyperlinks */
url_link.setAddress("http://www.google.com");
try {
file_link.setAddress((URLEncoder.encode("Encuesta de bienvenida","UTF-8")+"/"+"E18").replace("\\", "/").replace("+","%20"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("addres--> " + file_link.getAddress());
email_link.setAddress("mailto:test@gmail.com");
/* Attach these links to cells */
Row row = my_sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Take me to Google");
cell.setHyperlink(url_link);
row = my_sheet.createRow(1);
cell = row.createCell(1);
cell.setCellValue("Click to Open the file");
cell.setHyperlink(file_link);
row = my_sheet.createRow(2);
cell = row.createCell(2);
cell.setCellValue("Send an Email");
cell.setHyperlink(email_link);
/* Write changes to the workbook */
FileOutputStream out = new FileOutputStream(new File("C:/cell_hyperlink_example.xlsx"));
my_workbook.write(out);
out.close();
}
}