简体   繁体   中英

Working with hyperlinks in Aspose.Cells

I am generating an excel document using Aspose.Cells, and inside the document some fields will contain a URL. I would like to make the URL a clickable link. I have tried adding the link to the hyperlinks collection using

workSheet.Hyperlinks.Add(cell.Name, rowCount, columnCount, content);

This will add the link as desired but if the user sorts the document in Excel, the link will remain attached to the cell it originated from. The ability to sort in Excel is a requirement.

I have also tried

cell.Formula = $"=HYPERLINK(\"{content}\",\"{content}\")";

and then styling the cell as a hyperlink. This works okay, and the links will follow the cell with a sort. The downside is that until the user enables editing in Excel, the link will not be displayed.

Is there a better way to add hyperlinks to Excel with Aspose.Cells?

Please try the following sample code and read its comments. It works fine. Please see the screenshot that shows the output Excel file generated by the code. If you sort the links, they will sort correctly.

C#

//Create workbook
Workbook wb = new Workbook();

//Access first worksheet
Worksheet ws = wb.Worksheets[0];

//Add hyperlink in cell A1
int idx = ws.Hyperlinks.Add("A1", 1, 1, "https://forum.aspose.com/c/cells");
ws.Hyperlinks[idx].TextToDisplay = "Cells Link No: 11";

//Add hyperlink in cell A2
idx = ws.Hyperlinks.Add("A2", 1, 1, "https://forum.aspose.com/c/total");
ws.Hyperlinks[idx].TextToDisplay = "Total Link No: 16";

//Add hyperlink in cell A3
idx = ws.Hyperlinks.Add("A3", 1, 1, "https://forum.aspose.com/c/words");
ws.Hyperlinks[idx].TextToDisplay = "Words Link No: 29";

//Add hyperlink in cell A4
idx = ws.Hyperlinks.Add("A4", 1, 1, "https://forum.aspose.com/c/pdf");
ws.Hyperlinks[idx].TextToDisplay = "Pdf Link No: 13";

//Add hyperlink in cell A5
idx = ws.Hyperlinks.Add("A5", 1, 1, "https://forum.aspose.com");
ws.Hyperlinks[idx].TextToDisplay = "Forum Link No: 20";

//Add hyperlink in cell A6
idx = ws.Hyperlinks.Add("A6", 1, 1, "https://forum.aspose.com");
ws.Hyperlinks[idx].TextToDisplay = "Forum Link No: 15";

//Autofit columns
ws.AutoFitColumns();

//Save the output Excel file
wb.Save("output.xlsx");

Screenshot: 在此处输入图片说明

Note: I am working as Developer Evangelist at Aspose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM