How to extract link url from Excel cell

荒凉一梦 提交于 2019-12-11 07:16:48

问题


I have a c# webjob that downloads and then reads an Excel file. One of the columns contains links that I'd like to save in my database. I'm currently using ExcelDataReader to convert the Excel file to a DataSet and then looping through the rows to grab the data. After conversion the column in question at this point is only a string containing the link text.

From some other reading it sounds like in Excel, hyperlinks are stored elsewhere and that information isn't preserved when converting the Excel file to a DataSet.

I'm not set on using ExcelDataReader but would like to find a solution to extract these link URLs without having to pay for some third part software.

Here is the simple code I have so far as reference:

FileStream stream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;

DataSet result = excelReader.AsDataSet();

int count = 0;

foreach (DataRow row in result.Tables["WorkSheetName"].DataTable.Rows)
{
    var item = new myObject();

    item.Prop1 = long.Parse(row["Column3"].ToString());
    item.Prop2 = row["Column7"].ToString(); //The link, currently only seeing link text

    this.myDbContext.myTable.Add(item);
    await this.myDbContext.SaveChangesAsync();

    count += 1;
}

回答1:


I ended up being able to get the hyperlink data using EPPLUS to read my excel file.

Code:

var pck = new ExcelPackage(excelFileStream);
ExcelWorksheet ws = pck.Workbook.Worksheets.First();

DataTable dt = new DataTable(ws.Name);
int totalCols = ws.Dimension.End.Column;
int totalRows = ws.Dimension.End.Row;
int startRow = 3;
ExcelRange wsRow;
DataRow dr;
foreach (var firstRowCell in ws.Cells[2, 1, 2, totalCols])
{
    dt.Columns.Add(firstRowCell.Text);
}

for (int rowNum = startRow; rowNum <= totalRows; rowNum++)
{
    wsRow = ws.Cells[rowNum, 1, rowNum, totalCols];
    dr = dt.NewRow();
    int rowCnt = 0;
    foreach (var cell in wsRow)
    {
        if (rowCnt == 7)
        {
            if (cell.Hyperlink != null)
            {
                dr[cell.Start.Column - 1] = cell.Hyperlink.AbsoluteUri;
            }
        }
        else
        {
            dr[cell.Start.Column - 1] = cell.Text;
        }

        rowCnt++;
    }

    if (!String.IsNullOrEmpty(dr[7].ToString()))
    {
        dt.Rows.Add(dr);
    }
}

return dt;


来源:https://stackoverflow.com/questions/41727557/how-to-extract-link-url-from-excel-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!