[RoutePrefix("api/ExportGridAsExcel")]
public class ExportController : ApiController
{
//Excel Export Method.
[HttpPost]
[Route("")]
public void ExcelExport()
{
string gridModel = HttpContext.Current.Request.Params["TreeGridModel"];
GridProperties gridProperty = ConvertGridObject(gridModel);
ExcelExport exp = new ExcelExport();
exp.Export(gridProperty, (IEnumerable)gridProperty.DataSource, "Export.xlsx", ExcelVersion.Excel2010); //Here the System.NullReferenceException occurs, reffered in https://www.syncfusion.com/kb/3018/Null-Exception-while-exporting
}
//Grid Model conversion Method.
private GridProperties ConvertGridObject(string gridProperty)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
GridProperties gridProp = new GridProperties();
foreach (KeyValuePair<string, object> ds in div)
{
if (ds.Key == "filteredRecords")
{
string serialize = serializer.Serialize(ds.Value);
dynamic dynamicDataSource = new List<dynamic>();
var dataSource = serializer.Deserialize<IEnumerable<Dictionary<string, object>>>(serialize);
foreach (var dictionary in dataSource)
{
dynamic rowObject = new ExpandoObject();
foreach (var keyValuePair in dictionary)
{
((IDictionary<String, Object>)rowObject).Add(keyValuePair.Key, keyValuePair.Value);
}
dynamicDataSource.Add((dynamic)rowObject);
}
gridProp.DataSource = dynamicDataSource;
continue;
}
var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
if (property != null)
{
Type type = property.PropertyType;
string serialize = serializer.Serialize(ds.Value);
object value = serializer.Deserialize(serialize, type);
property.SetValue(gridProp, value, null);
}
}
return gridProp;
}
}