Search code examples
c#excellinq-to-excel

LinqToExcel get hyperlink value


I'm using LinqToExcel to read an excel file. Everything works fine, but it the content of a cell is a hyperlink, I only get the hyperlink text. I would like to get its URL/email.

try
{
    // Connection to the DB
    iRentDB db = new iRentDB();

    // Get excel file and work sheet
    string pathToExcelFile = @"Members_Export_1500068180.xls";
    string sheetName = "Members_Export_1500068180";

    var excelFile = new LinqToExcel.ExcelQueryFactory(pathToExcelFile);

    // Select all rows from Excel
    var rows = from c in excelFile.WorksheetNoHeader(sheetName)
               select c;
    foreach (var row in rows)
    {
        // Get and validate the email
        var email = row[8].Value.ToString();
    }
}catch (Exception any)
{
    Console.Write(any.ToString());
}

The cell I'm reading is a hyperlink. The cell content name is "Email" and the hyperlink value is [email protected]. On my C# code, the variable email = "Email". How can I set to the variable email the hyperlink value ("[email protected]")?

Thanks


Solution

  • Programmatically when you add content to worksheet, excel application does not automatically edit the cell to format and add hyperlink (like it would if you were manually typing into cell).

    I'm not sure if LinqToExcel has option to add Hyperlink, but you might consider using EPPlus, here is link: How to create a link inside a cell using EPPlus.

    With EPPlus you can practically do anything with excel, just like with Microsoft.Office.Interop.Excel, which mostly is used for desktop applications (sample with Interop):

        Excel.Worksheet ws;        
        ws.Hyperlinks.Add(ws.Cells[5,8], "[email protected]");
        ws.Hyperlinks.Add(ws.Range["B4"], "[email protected]");
    

    I know it's not the answer you are looking for, but my point is that hyperlinks won't be automatically added.