How to use Epplus with cells containing few rows

社会主义新天地 提交于 2019-12-06 06:13:16

Those are known as Merged cells. Values from merged cells are stored in the .Value property of the first cell in the merged range. This means we need to do just a little bit more work in order to read the value from a merged cell using EPPlus.

EPPlus provides us with a couple of properties that help us get to the correct reference though. Firstly we can use a cell's .Merge property to find out if it is part of a merged range. Then we can use the the worksheet's .MergedCells property to find the relevant range. It's then just a matter of finding the first cell in that range and returning the value.

So, in summary:

  1. Determine if the cell we need to read from is part of a merged range using .Merge
  2. If so, get the index of the merged range using the worksheet's .MergedCells property
  3. Read the value from the first cell in the merged range

Putting this together we can derive a little helper method to take a worksheet object and row/col indices in order to return the value:

static string GetCellValueFromPossiblyMergedCell(ExcelWorksheet wks, int row, int col)
{
    var cell = wks.Cells[row, col];
    if (cell.Merge)                                              //(1.)
    {
        var mergedId = wks.MergedCells[row, col];                //(2.)
        return wks.Cells[mergedId].First().Value.ToString();     //(3.)
    }
    else
    {
        return cell.Value.ToString();
    }
}

Worked example

If I have a domain class like this:

class ImportedRecord
{
    public string ChildName { get; set; }
    public string SubGroupName { get; set; }
    public string GroupName { get; set; }
}

that I wanted to read from a spreadsheet that looked like this:

Then I could use this method:

static List<ImportedRecord> ImportRecords()
{
    var ret = new List<ImportedRecord>();
    var fInfo = new FileInfo(@"C:\temp\book1.xlsx");
    using (var excel = new ExcelPackage(fInfo))
    {
        var wks = excel.Workbook.Worksheets["Sheet1"];
        var lastRow = wks.Dimension.End.Row;

        for (int i = 2; i <= lastRow; i++)
        {
            var importedRecord = new ImportedRecord
            {
                ChildName = wks.Cells[i, 4].Value.ToString(),
                SubGroupName = GetCellValueFromPossiblyMergedCell(wks,i,3),
                GroupName = GetCellValueFromPossiblyMergedCell(wks, i, 2)
            };
            ret.Add(importedRecord);
        }
    }

    return ret;
}

static string GetCellValueFromPossiblyMergedCell(ExcelWorksheet wks, int row, int col)
{
    var cell = wks.Cells[row, col];
    if (cell.Merge)
    {
        var mergedId = wks.MergedCells[row, col];
        return wks.Cells[mergedId].First().Value.ToString();
    }
    else
    {
        return cell.Value.ToString();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!