How to create a link inside a cell using EPPlus

后端 未结 6 652
醉酒成梦
醉酒成梦 2021-02-01 12:40

I am trying to figure out how to write a Hyperlink inside a cell using EPPlus instead of the cell containing the link text. I need it to be recognized as a link and be clickable

6条回答
  •  庸人自扰
    2021-02-01 13:31

    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).

提交回复
热议问题