Search code examples
c#excelexcel-interopepplus

How do I write this Excel Interop syntax in EPPLUS syntax


Someone suggested to me a method to improve my code by making it more manageable through the use of objects:

string[,] values = new string[15, 35];  //or objects
values[7, 7] = "2016";
values[7, 28] = drag24;
values[7, 33] = drag25;
values[10, 8] = digit1;
values[10, 11] = digit2;
// etc.

Range range = WS.Range[WS.Cells[1, 1], WS.Cells[15, 35]];
range.Value = values;

His suggestion, but since I moved from interop to EPPLUS, the following syntax no longer works.

Range range = WS.Range[WS.Cells[1, 1], WS.Cells[15, 35]];

What would a working form of this look like in EPPLUS Syntax?

Replacing it with this didnt work out right and replaced everything in the sheet:

ExcelRange range = WS.Cells["A1: AH106"]

Perhaps something like this?

= sheet.Cells["A1:,12:12,14:14"]

Solution

  • Not sure if this is exactly what you mean, but here's a simple example with a custom object, and arrays:

    Test object:

    class TestObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Populating a sheet with the custom object, and arrays:

    IEnumerable<TestObject> objectList = new List<TestObject>()
    {
        { new TestObject() {Id = 0, Name = "zero" } },
        { new TestObject() {Id = 1, Name = "one" } }
    };
    var values = new List<object[]>()
    { 
        new string[] { "one", "two" }, 
        new string[] { "three", "four" }
    };
    
    using (var package = new ExcelPackage())
    {
        var sheet = package.Workbook.Worksheets.Add("Sheet1");
        // note second parameter gives you headings
        sheet.Cells["A1"].LoadFromCollection<TestObject>(objectList, true);
        sheet.Cells["A4"].LoadFromArrays(values);
        File.WriteAllBytes(OUTPUT, package.GetAsByteArray());
    }