2
votes

I am converting a data table to excel which is working fine. I have 4 columns in data table. Column1 and Column2 are simple text. Column3 and Column4 are hyperlink url and display text. all 4 columns are exported as it is in excel with below code :

        string fileName = ConfigurationManager.AppSettings["filename"];
        string sheetName = System.IO.Path.GetFileNameWithoutExtension(fileName);
        using (XLWorkbook wb = new XLWorkbook())
        {               
            var ws = wb.Worksheets.Add(ptDataTable, sheetName);

            ws.Style.Font.FontName = "Arial";
            ws.Style.Font.FontSize = 10;
            ws.Style.Alignment.WrapText = true;
            ws.FirstRow().Style.Alignment.SetWrapText(true);

            ws.Style.Alignment.SetWrapText(true);
            ws.Style.Alignment.SetShrinkToFit(true);
            ws.Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;
            ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
            ws.Rows().AdjustToContents();
            ws.Columns().AdjustToContents();

            ws.Rows(2,200).Style.Fill.SetBackgroundColor((XLColor.Transparent));
            ws.Columns(9, 10).Width = 50.0;
            ws.Range("A2:J200").Style.Border.SetInsideBorder(XLBorderStyleValues.Thin);
            ws.Range("A2:J200").Style.Border.SetOutsideBorder(XLBorderStyleValues.Thin);


            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
        }

I want to create hyperlink with column3(url) and column4(display text) and this hyperlink will be 3 column in exported excel.

Any idea!

3

3 Answers

5
votes

You will have to loop through the cells and add the hyperlinks manually:

ws.Cell(rowNumber, columnNumber).Hyperlink = new XLHyperlink(@"http://www.yahoo.com");

You can find more info about hyperlinks in ClosedXML at https://github.com/ClosedXML/ClosedXML/wiki/Using-Hyperlinks

2
votes

If I am not mistaken, your code is using the ClosedXML library, not the OpenXMLSDK.

There are two ways to add hyperlinks in OpenXMLSDK:

0
votes

Further to @Francois Botha's earlier solution, it need not take much code.

e.g. in VB.NET, I just used the following code to convert a string column containing URLs(already populated from my SQLServer database query's resultant DataTable) to clickable links:

    For Each wsrow In wc.Rows
        wsrow.Cell("G").Hyperlink = New XLHyperlink(wsrow.Cell("G"))
    Next

UPDATE: No, that appeared to work - highlighted URL - but the link content is empty :( Works a treat. FYI I am using quite an old version of OpenXML, 0.68.1.*

*I tried upgrading ClosedXML yesterday but it broke some essential existing code and the image display capability did not work for me - I was too short of time to mess about with it further.