Не удается экспортировать данные сетки кендо в электронную таблицу Excel

Я экспортирую данные из Kendo Grid. Код в контроллере обрывается с ошибкой в ​​цикле foreach.

СООБЩЕНИЕ ОБ ОШИБКЕ

  -InvalidCastException-


{"Unable to cast object of type '<>f__AnonymousType2`6[System.DateTime,System.String,System.Int32,System.String,System.String,System.String]' to type 'ZoomAudits.DAL.TypedViewClasses.ReportPhoneSupportResultRow'."}

Трассировки стека:

в UtilityWebSite.Controllers.ReportsController.Export (запрос DataSourceRequest, модель ReportsPhoneSupportSearchVM) в c:\Users\texas_000\Desktop\UtilityWebSite\UtilityWebSite\Controllers\ReportsController.cs:строка 130 в lambda_method(Closure, ControllerBase, Object[]) в системе .Web.Mvc.ActionMethodDispatcher.Execute (контроллер ControllerBase, параметры Object[]) в System.Web.Mvc.ReflectedActionDescriptor.Execute (ControllerContext controllerContext, параметры IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2) в System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() в System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) в System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End() в System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (IAsyncResult asyncResult, тег объекта) в System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMet hod(IAsyncResult asyncResult) в System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c() в System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.‹>c__DisplayClass45.b__3e()

Я искал возможные ответы, но не могу понять, что нужно изменить? Проект настроен на LLBL, и я с ним не знаком. Любая помощь будет отличной. Если вам нужна дополнительная информация, пожалуйста, дайте мне знать. Спасибо

public FileResult Export([DataSourceRequest]DataSourceRequest request, ReportsPhoneSupportSearchVM model)
    {
        ReportPhoneSupportResultTypedView results = new ReportPhoneSupportResultTypedView();
        string[] userIds = model.UserId.Split(',');
        foreach (string userId in userIds)
        {
            int iUserId = 0;
            if (Int32.TryParse(userId, out iUserId))
            {

                RetrievalProcedures.FetchReportPhoneSupportResultTypedView(results, model.FromDate, model.ToDate, iUserId);
            }
        }

        var Results = from Reslt in results
                       select new 
                      {
                          ActivityDate = Reslt.ActivityDate,
                          Action = Reslt.Action,
                          Assignment = Reslt.Assignment,
                          Description = Reslt.Description,
                          Result = Reslt.Result,
                          ToFrom = Reslt.ToFrom
                      };


        //Get the data representing the current grid state - page, sort and filter
        IEnumerable ExcelResults = Results.ToDataSourceResult(request).Data;

        //Create new Excel workbook
        var workbook = new HSSFWorkbook();

        //Create new Excel sheet
        var sheet = workbook.CreateSheet();

        //(Optional) set the width of the columns
        sheet.SetColumnWidth(0, 10 * 256);
        sheet.SetColumnWidth(1, 50 * 256);
        sheet.SetColumnWidth(2, 50 * 256);
        sheet.SetColumnWidth(3, 50 * 256);

        //Create a header row
        var headerRow = sheet.CreateRow(0);

        //Set the column names in the header row
        headerRow.CreateCell(0).SetCellValue("ActivityDate");
        headerRow.CreateCell(1).SetCellValue("Assignment");
        headerRow.CreateCell(2).SetCellValue("Action");
        headerRow.CreateCell(3).SetCellValue("ToFrom");
        headerRow.CreateCell(2).SetCellValue("Result");
        headerRow.CreateCell(3).SetCellValue("Description");

        //(Optional) freeze the header row so it is not scrolled
        sheet.CreateFreezePane(0, 1, 0, 1);

        int rowNumber = 1;

        //Populate the sheet with values from the grid data
        foreach (ReportPhoneSupportResultRow ER in ExcelResults)
        {
            //Create a new row
            var row = sheet.CreateRow(rowNumber++);

            //Set values for the cells
            row.CreateCell(0).SetCellValue(ER.ActivityDate);
            row.CreateCell(1).SetCellValue(ER.Assignment);
            row.CreateCell(2).SetCellValue(ER.Action);
            row.CreateCell(3).SetCellValue(ER.ToFrom);
            row.CreateCell(2).SetCellValue(ER.Result);
            row.CreateCell(3).SetCellValue(ER.Description);
        }

        //Write the workbook to a memory stream
        MemoryStream output = new MemoryStream();
        workbook.Write(output);

        //Return the result to the end user

        return File(output.ToArray(),   //The binary data of the XLS file
            "application/vnd.ms-excel", //MIME type of Excel files
            "GridExcelExport.xls");     //Suggested file name in the "Save as" dialog which will be displayed to the end user

    }

person user3750212    schedule 17.06.2014    source источник
comment
пожалуйста, добавьте ошибку к вашему вопросу   -  person Marcelo Bezerra bovino    schedule 18.06.2014
comment
У меня он наверху. Спасибо   -  person user3750212    schedule 18.06.2014
comment
есть идеи? мне нужно опубликовать больше информации?   -  person user3750212    schedule 18.06.2014
comment
Похоже, что преобразование приведения типов является проблемой из вашего набора результатов. Вы отладили код и проверили содержимое объекта excelresults?   -  person David Shorthose    schedule 19.06.2014
comment
все данные есть?   -  person user3750212    schedule 19.06.2014
comment
Это потому, что это анонимный тип?   -  person user3750212    schedule 19.06.2014
comment
Я думаю, вам следует использовать конкретный класс вместо анонимного типа. Или используйте переменную 'results' напрямую. См. llblgen.com/TinyForum/.   -  person David Elizondo    schedule 19.06.2014
comment
Я понял, спасибо за помощь, хотя!   -  person user3750212    schedule 19.06.2014


Ответы (1)


Получил решение. используйте этот код в действии FileExport

ReportPhoneSupportResultTypedView results = new ReportPhoneSupportResultTypedView();
    string[] userIds = model.UserId.Split(',');
    foreach (string userId in userIds)
    {
        int iUserId = 0;
        if (Int32.TryParse(userId, out iUserId))
        {

            RetrievalProcedures.FetchReportPhoneSupportResultTypedView(results, model.FromDate, model.ToDate, iUserId);
        }
    }


    //Get the data representing the current grid state - page, sort and filter
    IEnumerable ExcelResults = ((IEnumerable)results).ToDataSourceResult(request).Data;
person user3750212    schedule 19.06.2014