How to create a link inside a cell using EPPlus
This is the other way to do:
var cell = sheet.Cells["A1"];
cell.Hyperlink = new Uri("http://www.google.com");
cell.Value = "Click me!";
I have tested. It works fine.
The below code worked fine with me.
string FileRootPath = "http://www.google.com";
_Worksheet.Cells[intCellNumber, 1].Formula = "HYPERLINK(\"" + FileRootPath + "\",\"" + DisplayText + "\")";
I hope this would help you.
Happy coding!!
There's a few ways to go about it:
-
To use URI, then set a human readable name:
var cell = sheet.Cells["A1"]; cell.Hyperlink = new Uri("https://www.google.com"); cell.Value = "Click me!";
-
To use ExcelHyperLink and set a human readable name using object initializer :
var cell = sheet.Cells["A1"]; cell.Hyperlink = new ExcelHyperLink("https://www.google.com") { Display = "Click me!" };
-
To use =Hyperlink() formula:
var cell = sheet.Cells["A1"]; cell.Formula = string.Format("HYPERLINK({0},{1})", "https://www.google.com", "Click me!"); cell.Calculate();
Based on provided answers and documentation I was able to create an extension method that also deals with proper hyperlink formatting. It creates a named style, if needed, and use that style for all subsequent hyperlinks:
public static void WriteHyperlink(this ExcelRange cell, string text, string url, bool excelHyperlink = false, bool underline = true)
{
if (string.IsNullOrWhiteSpace(text))
return;
// trying to reuse hyperlink style if defined
var workBook = cell.Worksheet.Workbook;
string actualStyleName = underline ? HyperLinkStyleName : HyperLinkNoUnderlineStyleName;
var hyperlinkStyle = workBook.Styles.NamedStyles.FirstOrDefault(s => s.Name == actualStyleName);
if (hyperlinkStyle == null)
{
var namedStyle = workBook.Styles.CreateNamedStyle(actualStyleName);
namedStyle.Style.Font.UnderLine = underline;
namedStyle.Style.Font.Color.SetColor(Color.Blue);
}
if (excelHyperlink)
cell.Hyperlink = new ExcelHyperLink(url) { Display = text };
else
{
cell.Hyperlink = new Uri(url);
cell.Value = text;
cell.StyleName = actualStyleName;
}
}
Without the styling, the hyperlink will look just as regular text, if cell.Hyperlink = new Uri(url);
is used without explicit styling (although the cursor will properly indicate that the text is actually a hyperlink text).