Import/Export using Infragistics Excel in MVC3 Applications

Jordan Tsankov / Friday, March 9, 2012

Using the Infragistics Document library , you have access to a great set of tools to manipulate Microsoft Excel files. Infragistics Excel gives you an API to modify and save server-side data into an Excel document , as well as load up and process a file that a client specifies. In this blog post we’ll cover a basic scenario for both of these cases – showing you how to export data that has been fed to an Infragistics Grid , as well as using a local Excel file and populate an Infragistics jQuery Grid with its contents.

Let’s get on with it !

Initial Preparation

Before you can use the Infragistics Excel library , you need to add a few references to your project. First off, open the folder where you installed your Infragistics products, then navigate to jQuery/mvc/MVC3/bin/ and reference the Infragistics.Web.Mvc.dll. After that, you go to jQuery/mvc/Common/bin/ and reference both Infragistics.Web.Mvc.Documents.Core.dll and Infragistics.Web.Mvc.Documents.Excel.dll.

Exporting

To showcase how exporting works , we will set up a pretty simple MVC3 application. We have a controller that feeds data to an Infragistics jQuery Grid. The same controller is also responsible for loading up a .xls file and then populating a collection with objects which have been ‘parsed’ from the Excel file. That collection is finally used to supply a new Infragistics jQuery Grid with data. Here’s the code for the controller:

 

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5: using System.Web.Mvc;
   6: using System.Security;
   7: using ExcelExport.Models;
   8: using Infragistics.Web.Mvc;
   9: using Infragistics.Documents.Excel;
  10:  
  11: namespace ExcelExport.Controllers
  12: {
  13:     public class HomeController : Controller
  14:     {
  15:         //
  16:         // GET: /Home/
  17:  
  18:         public ActionResult Index()
  19:         {
  20:             return View(SimpleItem.GetItemsList().AsQueryable());
  21:         }
  22:  
  23:         [HttpPost]
  24:         public void Export()
  25:         {
  26:             List<SimpleItem> items = SimpleItem.GetItemsList();
  27:             Workbook workbook = new Workbook(WorkbookFormat.Excel97To2003);
  28:             Worksheet sheet = workbook.Worksheets.Add("Sheet 1");
  29:             int i = 1;
  30:             foreach (SimpleItem item in items)
  31:             {
  32:                 sheet.Rows[i].Cells[0].Value = item.Text1;
  33:                 sheet.Rows[i].Cells[1].Value = item.Text2;
  34:                 i++;
  35:             }
  36:             Save(workbook);
  37:         }
  38:  
  39:         private void Save(Workbook document)
  40:         {
  41:             string fileName = "Document1.xls";
  42:             Response.Clear();
  43:             Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
  44:             Response.ContentType = "application/octet-stream";
  45:             document.SetCurrentFormat(WorkbookFormat.Excel97To2003);
  46:             document.Save(Response.OutputStream);
  47:             Response.End();
  48:         }
  49:  
  50:         public ActionResult Import() {
  51:             Workbook wb = Workbook.Load(Server.MapPath("~/Content/Document1.xls"));
  52:             Worksheet sheet = wb.Worksheets[0];
  53:             List<SimpleItem> data = new List<SimpleItem>();
  54:  
  55:             foreach (WorksheetRow row in sheet.Rows)
  56:             {
  57:                 if (row.Cells[0].Value != null && row.Cells[1].Value != null)
  58:                 {
  59:                     SimpleItem item = new SimpleItem 
  60:                     {
  61:                         Text1 = row.Cells[0].Value.ToString(),
  62:                         Text2 = row.Cells[1].Value.ToString()
  63:                     };
  64:  
  65:                     data.Add(item);
  66:                 }
  67:  
  68:             }
  69:             return View(data.AsQueryable());
  70:         }
  71:     }
  72: }

The Index ActionResult is the one responsible for the main view – the one we have our initial grid on. This is why we send the collection of data as the view’s model – so that the grid has a data model to bind to.

 

In Export we handle incoming POST requests, which are in this case used only to signal that the user wants to export the model data collection. We create a new Workbook object, which is technically a code representation of an Excel file. Then we add a worksheet to this workbook and simply write data in each row , in the first two cells.

Attention then gets shifted towards the Save method, which attaches the resulting Excel file to the response header and returns the response.

And here you have the model class:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5:  
   6: namespace ExcelExport.Models {
   7:     public class SimpleItem {
   8:         public String Text1 { get; set; }
   9:         public String Text2 { get; set; }
  10:  
  11:         public static List<SimpleItem> GetItemsList() {
  12:             List<SimpleItem> items = new List<SimpleItem>();
  13:             for (int i = 0; i < 100; i++) {
  14:                 items.Add(new SimpleItem { Text1 = "Item " + i, Text2 = "Text " + i });
  15:             }
  16:             return items;
  17:         }
  18:     }
  19: }

Nothing staggering here – a function that yields a list with some items added inside. We use that method in the controller in order to set the view’s model.

And finally here is the Index view , which holds the initial grid:

   1: @using Infragistics.Web.Mvc;
   2: @model IQueryable<ExcelExport.Models.SimpleItem>
   3:  
   4: @{
   5:     ViewBag.Title = "Index";
   6: }
   7:  
   8: @(
   9: Html.Infragistics()
  10: .Grid(Model)
  11: .ID("grid1")
  12: .Width("300px")
  13: .Height("500px")
  14: .AutoGenerateColumns(true)
  15: .DataBind()
  16: .Render()
  17: )
  18:  
  19: <form action="Home/Export" method="post">
  20: <button type="submit" value="Export">Export</button>
  21: </form>
  22: <form action="Home/Import">
  23: <button type="submit" value="Import">Import</button>
  24: </form>
  25:  

 

Importing

As stated above , our goal is to have an external Microsoft Excel file used as a data source for an Infragistics jQuery Grid. We have one such file prepared in the /Contents folder of our sample project – here’s the one:

Document Location Excel

In this Excel file , we have the first two columns populated with text in the following pattern:

Import 0 Item 0
Import 1 Item 1
Import 2 Item 2
Import 3 Item 3
Import 4 Item 4

 

This should effectively translate to a grid with two columns , populated with the same entries. The function that takes care of this is in the HomeController , and it’s called Import.

 

 

   1: public ActionResult Import() {
   2:             Workbook wb = Workbook.Load(Server.MapPath("~/Content/Document1.xls"));
   3:             Worksheet sheet = wb.Worksheets[0];
   4:             List<SimpleItem> data = new List<SimpleItem>();
   5:  
   6:             foreach (WorksheetRow row in sheet.Rows)
   7:             {
   8:                 if (row.Cells[0].Value != null && row.Cells[1].Value != null)
   9:                 {
  10:                     SimpleItem item = new SimpleItem 
  11:                     {
  12:                         Text1 = row.Cells[0].Value.ToString(),
  13:                         Text2 = row.Cells[1].Value.ToString()
  14:                     };
  15:  
  16:                     data.Add(item);
  17:                 }
  18:  
  19:             }
  20:             return View(data.AsQueryable());
  21:         }

What we do is we load a workbook from a physical file and then open up the first worksheet. We then iterate through all the available rows and create a new SimpleItem instance whenever both of the row’s first and second cells have any value in them. The resulting SimpleItem object we add to a list.

Finally, we return the view together with the list , so it can be used as a data model by our new Infragistics jQuery Grid. Here’s the resulting view:

   1: @using Infragistics.Web.Mvc;
   2: @model IQueryable<ExcelExport.Models.SimpleItem>
   3:            
   4: @{
   5:     ViewBag.Title = "Import";
   6:     Layout = "~/Views/Shared/_Layout.cshtml";
   7: }
   8:  
   9: <h2>Imported from a XML file</h2>
  10:  
  11: @(
  12: Html.Infragistics()
  13: .Grid(Model)
  14: .ID("grid1")
  15: .Width("300px")
  16: .Height("500px")
  17: .AutoGenerateColumns(true)
  18: .DataBind()
  19: .Render()
  20: )
  21:  

And that’s pretty much all there is to it ! You will see the same data from the Excel file loaded into your jQuery grid.

Conclusion

In a case where your application is grid-heavy , what better way to let users preserve data than enable them to export it locally to a spreadsheet? And if you need two-way interaction – then why not let the same users upload the spreadsheet back to you so you update your server data? With Infragistics Excel , this is all entirely possible and as you’ve seen in the examples above – it is not that hard to achieve as well.

You may acquire further information about exporting your grid data by checking out the official sample.

Or you may wish to download the sample project for this blog post by clicking here.

ExcelExport.zip