Search code examples
c#exceldatatableexcelpackage

Adding href to Excel Export C#


I need help with this issue, I'm exporting my datatable into an excel file which works fine. the problem is I'm trying to make one of the columns a hyperlink to a document but as it starts to build out the excel file I get this error. Thank you in advance for your help.

'This operation is not supported for a relative URI.'

using OfficeOpenXml;
using OfficeOpenXml.Table;

public void ExportExcelFile(System.Data.DataTable excelData, string excelSheetName)
    {
        using (var package = new ExcelPackage())
        {
            ExcelWorksheet ws = package.Workbook.Worksheets.Add(excelSheetName);

            int rowCount = 1;
            foreach (DataRow rw in excelData.Rows)
            {
                //excelData.Columns.RemoveAt(0);
                rowCount += 1;
                for (int i = 1; i < excelData.Columns.Count + 1; i++)
                {
                    // Add the header the first time through 
                    if (rowCount == 2)
                    {
                        ws.Row(1).Style.Font.Bold = true;
                        ws.Cells[1, i].Value = excelData.Columns[i - 1].ColumnName;
                    }
                    ws.Column(i).AutoFit();

                    //THIS IS THTE PROBLEM
                    string hyperlink = "<a href='~/Documents/DownloadFile.aspx?id=" + rw["DocPk"].ToString() + "'>" + rw["Drawing Id"].ToString() + "</a>";
                    ws.Cells[i, 7].Hyperlink = new Uri(hyperlink, UriKind.RelativeOrAbsolute);  

                    ws.Cells[rowCount, i].Value = rw[i - 1].ToString();
                }
            }

            MemoryStream Result = new MemoryStream();
            package.SaveAs(Result);
            Response.ClearContent();
            Response.OutputStream.Write(Result.GetBuffer(), 0, Result.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            byte[] byteArray = Result.ToArray();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + excelSheetName + ".xlsx");
            Response.AddHeader("Content-Length", byteArray.Length.ToString());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.BinaryWrite(byteArray);
            Response.End();
        }
    }

Solution

  • Excel simply doesn't support relative URLs, as an Excel document doesn't have a URL to be relative to. You'll need to fully qualify all your URLs:

    string hyperlink = String.Format("http://{0}/Documents/DownloadFile.aspx?id={1}",
       Page.Request.Url.Host,
       rw["DocPk"].ToString());
    
    ws.Cells[rowCount, i].Hyperlink = new Uri(hyperlink, UriKind.Absolute);
    ws.Cells[rowCount, i].Value = rw["Drawing Id"];
    

    Note the fully qualified URL, complete with http:// as well as the UriKind.Absolute.