EPPlus - 未填充命名范围

时间:2014-02-19 05:36:42

标签: c# excel epplus

我正在使用EPPLus打开Excel Spreadsheets并尝试从命名范围读取。命名范围为空。

我使用这个错误,还是EPPlus的问题

代码

        var package = new ExcelPackage();

        using (var stream = File.OpenRead(tmpExcel))
        {
            package.Load(stream);
        }

        var worksheet = package.Workbook.Worksheets["Common-Lookup"];

        using (ExcelNamedRange namedRange = worksheet.Names["LupVerticalSettings"])
        {
            for (var row = namedRange.Start.Row; row <= namedRange.End.Row; row++)
            {
                for (var col = namedRange.Start.Column; col <= namedRange.End.Column; col++)
                {
                    _.Nv(worksheet.Cells[row, col].Address, worksheet.Cells[row, col].Text);
                    //worksheet.Cells[rowIndex, columnIndex].Value = "no more hair pulling";
                }
            }
        }

Excel看起来像这样

Excel Named Range

清空命名范围

Empty Named Range

1 个答案:

答案 0 :(得分:13)

我解决了我的问题,我会在这里为那些可能需要它的人提出答案

    var package = new ExcelPackage();

    using (var stream = File.OpenRead(tmpExcel))
    {
        package.Load(stream);
    }

    var worksheet = package.Workbook.Worksheets["Common-Lookup"];

    // Access Named Ranges from the ExcelWorkbook instead of ExcelWorksheet
    //using (ExcelNamedRange namedRange = worksheet.Names["LupVerticalSettings"])

    // use package.Workbook.Names instead of worksheet.Names
    using (ExcelNamedRange namedRange = package.Workbook.Names["LupVerticalSettings"])
    {
        for (var row = namedRange.Start.Row; row <= namedRange.End.Row; row++)
        {
            for (var col = namedRange.Start.Column; col <= namedRange.End.Column; col++)
            {
                _.Nv(worksheet.Cells[row, col].Address, worksheet.Cells[row, col].Text);
                //worksheet.Cells[rowIndex, columnIndex].Value = "no more hair pulling";
            }
        }
    }