• North American Sales: 1-800-231-8588
  • Global Contacts
  • My Account
Infragistics Infragistics
Menu
  • North American Sales: 1-800-321-8588
  • My Account
    • Sign In/Register
  • Design & DevelopmentDesign & Develop
    • Best Value
      Infragistics Ultimate The complete toolkit for building high performing web, mobile and desktop apps.
      Indigo.Design Use a unified platform for visual design, UX prototyping, code generation and application development.
    • Web
      Ignite UI for Angular Ignite UI for JavaScript Ignite UI for React Ultimate UI for ASP.NET Indigo.Design
    • Desktop
      Ultimate UI for Windows Forms Ultimate UI for WPF
      Prototyping
      Indigo.Design
    • Mobile
      Ultimate UI for Xamarin Ultimate UI for iOS Ultimate UI for Android
    • Automated Testing Tools
      Test Automation for Micro Focus UFT: Windows Forms Test Automation for Micro Focus UFT: WPF Test Automation for IBM RFT: Windows Forms
  • UX
    • Indigo.Design Desktop Collaborative prototyping and remote usability testing for UX & usability professionals
    • Indigo.Design A Unified Platform for Visual Design, UX Prototyping, Code Generation, and App Development
  • Business Intelligence
    • Reveal Embedded Accelerate your time to market with powerful, beautiful dashboards into your apps
    • Reveal App Empower everyone in your organization to use data to make smarter business decisions
  • Team Productivity
  • Learn & Support Support
    • Help & Support Documents
    • Blogs
    • Forums
    • Product Ideas
    • Reference Applications
    • Customer Stories
    • Webinars
    • eBook & Whitepapers
    • Events
  • Free Trials
  • Pricing
    • Product Pricing / Buy Online
    • Renew Existing License
    • Contact Us
ASP.NET
  • Product Platforms
  • More
ASP.NET
ASP.NET WebDataGrid : Import data from Excel & Export to Excel, PDF or XPS
  • Blog
  • Files
  • Wiki
  • Mentions
  • Tags
  • More
  • Cancel
  • New
ASP.NET requires membership for participation - click to join
  • ASP.NET
  • Accessing Extra Data in Data Bound Controls
  • ASP.NET Performance - A Place To Start
  • +Building an Ajax Master/Detail Page with the WebDataGrid
  • Building WebParts with NetAdvantage ASP.NET Controls
  • Data Binding the WebDataGrid to Common Data Sources
  • Getting Started with NetAdvantage ASP.NET
  • HTML5 Mode and Other Goodness in the WebRating Control
  • Implementing WebDataGrid Client Side Search
  • Introduction to the Infragistics Web Drag and Drop Framework
  • Learn to Build a WebDataGrid Custom Pager
  • Understanding Script Combining
  • Using ADO.NET to Perform CRUD Operations with the WebDataGrid
  • WebDataGrid 101: Fill the Grid with Data and Change the Look and Feel
  • -WebDataGrid : Import data from Excel & Export to Excel, PDF or XPS
    • Show wait indicator during WebDataGrid’s AJAX Requests
  • WebDataGrid Client-Side CRUD
  • WebDataGrid DataViewState vs ViewState
  • WebDataGrid Validation

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

If you’ve used our Excel or Document APIs, then you may already know where is article 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.
   myDataTable.Columns.Add(myDataColumn);

   //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); 
   importGrid.Columns.Add(bdf); }

 

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] = internalWorkBook.Worksheets["Customers"].Rows[rowIndex].Cells[columnIndex].Value; 
   } 
   
   //Add The Row to a DataTable 
   myDataTable.Rows.Add(myDataRow); 
}

 

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; importGrid.DataBind();

 

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 
theWorkbook.Save(theStream); 

//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); 
theStream.Close(); 
Response.Clear(); 
Response.AddHeader("content-disposition", "attachment; filename=ExportedTo.xls"); 
Response.BinaryWrite(byteArr); 
Response.End();

 

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.

 

Manually Create Excel Files

Excel I/0

Coloring Keywords in your Excel Worksheet

Export WPF XamDataGrid to Excel

Export WinChart to Excel

Export WinTree to Excel

 

Happy Coding !

  • Share
  • History
  • More
  • Cancel
Related
Recommended