dynamically create the dataset using a key-value pair list by using the Expando

Posted by: damian.haynes on 2 December 2020, 8:46 am EST

  • Posted 2 December 2020, 8:46 am EST

    Hey there,

    Using the template function in .net Core 3.1 code.

    We created a class with a Date Field and a List of string values. This DataSet merged successfully.

    We then tried to dynamically create the same using a key-value pair list by using the Expando class. But this failed, so we trimmed it back to just one item the Date Field.

    A1 B1
    FileDate {{ds.FileDate}}

    Using the immediate window in VS we can see the FileDate
    expando.FileDate
    {1/01/2020 3:21:00 PM}
    Date: {1/01/2020 12:00:00 AM}
    Day: 1
    DayOfWeek: Wednesday
    DayOfYear: 1
    Hour: 15
    Kind: Unspecified
    Millisecond: 0
    Minute: 21
    Month: 1
    Second: 0
    Ticks: 637134888600000000
    TimeOfDay: {15:21:00}
    Year: 2020

    The exception raised is
    System.ArgumentException: 'Can't find field or property 'FileDate' of type 'System.Collections.Generic.KeyValuePair`2

    The test method is

    [TestMethod]
    public void Generate_SampleData_SavesExcelFile()
    {
    var templateFileLocation = @"C:\samplefiles\input.xltx";
    var outboundFileLocation = @"C:\samplefiles\gen";

    // Create a Key/Value pair for all fields and the Grid
    dynamic expando = new ExpandoObject();
    IDictionary<string, object> expandoDic = (IDictionary<string, object>)expando;

    // Fields
    expandoDic.Add("FileDate", new DateTime(2020, 1, 1, 15, 21, 00));

    // Excel
    Workbook workbook = new Workbook();
    workbook.Open(templateFileLocation);

    //Add data source
    workbook.AddDataSource("ds", expando);

    //Invoke to process the template
    workbook.ProcessTemplate();
    workbook.Save(@$"{outboundFileLocation}\file_{DateTime.Now:yyyy_MM_dd_HHmmss}.xlsx");
    }

    Is there something wrong in the above code, or this method is not supported?

    Thanks,
    Damian.
  • Marked as Answer

    Replied 3 December 2020, 10:27 pm EST

    Hi Damian,

    Sorry, but we do not face any kind of error at our end. Please see the attached sample and let us know if you are doing anything else.

    Also, the object that you are assigning to the data source is not supported. Please see the documentation below to see how you can data bind the excel:
    https://www.grapecity.com/documents-api-excel/docs/online/data-binding.html

    If you have any other issues then please let us know.

    Regards,
    Prabhat Sharma.
  • Replied 3 December 2020, 10:27 pm EST

    ExpandoObject.zip
Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels