Monday, May 2, 2016

How do I allow users to export GridViews to Excel sheets in DevExpress' MVC paradigm?

The example here is pretty convoluted and even includes a few methods which are not used, but it basically suggests that you'd have a button in your view like so:

@using (Html.BeginForm("Index", "Exporting"))
{
   <input type="submit" value="Export" />
}

 
 

Assuming NorthwindDataProvider.GetCustomers() is what hydrates our grid lets go ahead and use that to also hydrate our Excel sheet. The Excel sheet does not need to read directly from the GridView. This is going to hit an action like so:

using System;
using System.Web.Mvc;
using Modernity.Models;
namespace Modernity.Controllers
{
   public class ExportingController : Controller
   {
      public ActionResult Index()
      {
         Object data = NorthwindDataProvider.GetCustomers();
         return ReportExporter.MakeExcelSheet(data);
      }
   }
}

 
 

My helper class for returning the ActionResult is below. GridViewSettings is a DevExpress thing found in the DevExpress.Web.Mvc namespace.

using System;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using DevExpress.XtraPrinting;
namespace Modernity.Models
{
   public static class ReportExporter
   {
      public static ActionResult MakeExcelSheet(Object data)
      {
         GridViewSettings gridViewSettings = new GridViewSettings();
         gridViewSettings.Name = "report";
         ActionResult actionResult = GridViewExtension.ExportToXls(gridViewSettings,
               data, new XlsExportOptionsEx {ExportType =
               DevExpress.Export.ExportType.WYSIWYG});
         return actionResult;
      }
   }
}

 
 

One may make an Adobe Acrobat PDF instead of an Excel sheet by making the second the last line of code immediately above look like so:

ActionResult actionResult = GridViewExtension.ExportToPdf(gridViewSettings, data);

No comments:

Post a Comment