11

我有一个使用 EPPlus 以编程方式填充的 Excel 文件。

我尝试了以下方法:

// provides access to named ranges, does not appear to work with single cells
worksheet.Names["namedCell1"].Value = "abc123";

// provides access to cells by address
worksheet.Cells["namedCell1"].Value = "abc123";

以下确实有效 - 所以我知道我至少很接近。

worksheet.Cells["A1"].Value = "abc123";
4

1 回答 1

14

实际上,它有点误导。命名范围存储在workBOOK级别而不是workSHEET级别。因此,如果您执行以下操作:

[TestMethod]
public void Get_Named_Range_Test()
{
    //http://stackoverflow.com/questions/30494913/is-there-a-way-to-get-named-cells-using-epplus

    var existingFile = new FileInfo(@"c:\temp\NamedRange.xlsx");
    using (var pck = new ExcelPackage(existingFile))
    {
        var wb = pck.Workbook; //Not workSHEET
        var namedCell1 = wb.Names["namedCell1"];

        Console.WriteLine("{{\"before\": {0}}}", namedCell1.Value);
        namedCell1.Value = "abc123";
        Console.WriteLine("{{\"after\": {0}}}", namedCell1.Value);
    }
}

你在输出中得到这个(使用一个带有虚拟数据的 excel 文件):

{"before": Range1 B2}
{"after": abc123}
于 2015-05-28T21:06:36.973 回答