WebDataGrid - How to Import data from Excel & Export to Excel, PDF or XPS

[Infragistics] Murtaza Abdeali / Friday, December 12, 2008
If you’ve used our Excel or Document APIs, then you may already know where is post is headed. There have been numerous posts on how our Excel and Document APIs can be used to import and export data when working with our controls. In this post, we will focus on the newly released WebDataGrid control. Currently, it doesn’t have built-in support for exporting contents to Excel, PDF or XPS, ofcourse something that will be included in future. Here you can learn how to use the Excel API's load method to grab data from an excel sheet and display it within the WebDataGrid. Once the data is connected to the grid, you can then let the user do any grid operations like filter, sort, edit..etc. Once the user decides to export the displaying data, you can use the same API Engines to export the modified data and view back to Excel, PDF or XPS formats.
If you are only interested in learning how to export your data, you can skip the first section below.
Importing Data
Let’s start off by assigning some local variables that are going to help us accomplish the task.
//Create the temporary table to store data
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
DataRow myDataRow;
//MIN/MAX Values used to frame the working size of the Excel data to be imported.
int minCellRow = Int32.MaxValue;
int maxCellRow = Int32.MinValue;
int minCellColumn = Int32.MaxValue;
int maxCellColumn = Int32.MinValue;
Now, using an Excel sheet that has the NorthWind customer data, call the load method off of the Excel API to read the data and then construct a dataset.
Workbook internalWorkBook = Workbook.Load(Request.PhysicalApplicationPath + "Northwind.xls");
The load method will read the excel contents and return us an Excel workbook object. Once we have the workbook, we can search for the work sheet that contains the data and start constructing our data object that we will later bind to our WebDataGrid. In this example we are using a DataTable.
First, need to determine the bounds of our data, the column structure so that we can create the skeleton our data object accordingly. Using the workbook object, we can iterate through the rows and cells to determine the max and min of cells and rows that are contained within our worksheet that we want to load in our WebDataGrid.
foreach (Infragistics.Excel.WorksheetRow row in internalWorkBook.Worksheets["Customers"].Rows)
    foreach (Infragistics.Excel.WorksheetCell cell in row.Cells)
         if (cell.Value != null)
              //Logic For Determining the Range of Rows/Columns in the Excel File.
              minCellRow = Math.Min(minCellRow, cell.RowIndex);
              maxCellRow = Math.Max(maxCellRow, cell.RowIndex);
              minCellColumn = Math.Min(minCellColumn, cell.ColumnIndex);
              maxCellColumn = Math.Max(maxCellColumn, cell.ColumnIndex);
After we’ve collected the structural infromation of our worksheet, we can create columns for our datatable, and at the same time construct the columns of our WebDataGrid too. Here is where you can modify or remove colunms that you don’t want to import or setup properties on the WebDataGrid columns that you are creating.
for (int i = minCellColumn; i <= maxCellColumn; i++)
    //Get the column name
    string columnName =
            internalWorkBook.Worksheets["Customers"].Rows[minCellRow].Cells[ i].Value.ToString();
    //The export that was demonstrated earlier utilizes the first row
    //for the column header.  We can now use that to give column names.
    myDataColumn = new DataColumn(columnName);
    //Add the columns to the datatable.
    //Create WebDataGrid Columns and enable settings
    BoundDataField bdf = new BoundDataField(true);
    bdf.DataFieldName = columnName;
    bdf.Key = columnName;
    bdf.Header.Text = columnName;
    bdf.Width = Unit.Pixel(100);
Finally, now it’s time to push the data from our worksheet into our DataTable.
for (int rowIndex = minCellRow + 1; rowIndex <= maxCellRow; rowIndex++)
       //Create a new DataRow
       myDataRow = myDataTable.NewRow();
       //Loop through the columns and associate the value to each cell
       for (int columnIndex = minCellColumn; columnIndex <= maxCellColumn; columnIndex++)
            myDataRow[columnIndex] =
       //Add The Row to a DataTable
Ok, so now we have all we need in our DataTable, our WebDataGrid columns are setup as we want, let's go ahead and databind our WebDataGrid.
//Set the primary key so that the WebDataGrid can perform Auto Crud
myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns["CustomerID"] };
//ImportGrid below is the grid that we have on our page
importGrid.DataSource = myDataTable;
To download the sample that includes the source code, use the link at the end of this post.
Note: The code assumes that you have the XLS file on the server, so that you can feed it in the Excel engine and can import data within the WebDataGrid. If you want to extend the behavior such that the client should be able to import an Excel file from his/her machine, then you will have to add the ability for the client to be able to upload that file onto the server first. Once, it is on the server, you can then simply use the import method to extract data from it.

Exporting Data

The idea behind exporting data to any of the formats using the APIs is the same. Basically, you iterate through the WebDataGrid columns first to create the column structure of the exported document and then iterate through the rows of the WebDataGrid to create rows for the data you want to export. Since the code is mostly the same when exporting to any of the formats, we will only going to run through  exporting to excel in the post, you can download the sample from link below to get code for all formats.
First we need to create the workbook and worksheet object of excel that we are going to export our data into and some helper variables that will help us accomplish the task.
//Create workbook and worksheet object for Excel
Workbook theWorkbook = new Workbook();
Worksheet theWorkSheet = theWorkbook.Worksheets.Add("WorkSheet1");
int iRow = 1;
int iCell = 1;
Now, iterate through the WebDataGrid columns to create the excel sheet columns and go through your rows to fill up the cells in those columns.
//Iterate through the columns of the WebDataGrid and create
// columns within the worksheet that will be exported.
foreach(GridField gridField in this.WebDataGrid1.Columns)
    iRow = 1;
     theWorkSheet.Rows[iRow].Cells[iCell].Value = gridField.Header.Text;
     theWorkSheet.Columns[iCell].Width = 5000;
     iRow += 1;
     //Now iterate through the grid rows to add rows to the worksheet
     foreach(GridRecord gridRecord in this.WebDataGrid1.Rows)
          theWorkSheet.Rows[iRow].Cells[iCell].Value = gridRecord.Items[iCell-1].Text;
 iRow += 1;
      iCell += 1;
In the sample attached you will find some extra code for formatting your cells while they are being exported. Once you’ve create your worksheet and exported the data, you can now go ahead and write the excel sheet to your stream, so that the client can view it.
//Create the Stream class
System.IO.MemoryStream theStream = new System.IO.MemoryStream();
//Write the in memory Workbook object to the Stream
//Create a Byte Array to contain the stream and send the exported sheet to the client
byte[] byteArr = (byte[])Array.CreateInstance(typeof(byte), theStream.Length);
theStream.Position = 0;
theStream.Read(byteArr, 0, (int)theStream.Length);
Response.AddHeader("content-disposition", "attachment; filename=ExportedTo.xls");
That’s it! Using the code samples above you should be able to import your data from Excel and export it to Excel, PDF or XPS using the APIs that we ship along with our product. Download the source code of this tutorial from the link below.

Download Source Code: ExportWebDataGridContents.zip

Note: Sample is using 2008 Volume 3 of our control set and uses C#.  
These APIs demonstrated here are not directly connected to any control or component, so you can use it for any custom exporting requirement that you may have. To view more examples on the usage of the API, please check out the following resource.
Happy Coding !