Search code examples
c#excelopenxmlepplusexcelpackage

How to set value of Excel cell by name instead of using coordinates with EPPlus?


I am able to set cell values using EPPlus:

var template = new FileInfo(Server.MapPath("~/App_Data/my_template.xlsx"));
var pck = new ExcelPackage(template);
var ws = pck.Workbook.Worksheets.First();
ws.Cells[15, 4].Value = 66; 
ws.Cells["B1"].Value = 55;

Instead of addressing the target cell by its coordinates I would like to use a named cell/variable "profits".

ws.Range("profits").Value = 66;

However, EPPlus does not support ws.Range(...).

=> Is it nevertheless possible to do so? How would I write an extension method that provides the wanted functionality?

Related articles/questions:

a) Doc for EPPlus:

http://epplus.codeplex.com

b) How to use named cells/variables in Excel:

https://www.computerhope.com/issues/ch000704.htm

What's the RIGHT way to reference named cells in Excel 2013 VBA? (I know I'm messing this up)

c) Libraries for creating Excel Files with C#

Create Excel (.XLS and .XLSX) file from C#


Solution

  • var profits = pck.Workbook.Names["profits"];
    profits.Value = 66;
    

    from

    Is there a way to get 'named' cells using EPPlus?

    It is also possible to set the values for a named range:

    var ws = pck.Workbook.Worksheets.First();
    using (var namedRange = pck.Workbook.Names["MyNamedRange"])
          {
            for (int rowIndex = namedRange.Start.Row; rowIndex <= namedRange.End.Row; rowIndex++)
            {
              for (int columnIndex = namedRange.Start.Column; columnIndex <= namedRange.End.Column; columnIndex++)
              {
                ws.Cells[rowIndex, columnIndex].Value = 66;
              }
            }
          }
    

    from

    EPPlus, Find and set the value for a Named Range