65.9K
CodeProject is changing. Read more.
Home

Export DataGrid to Excel

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.23/5 (81 votes)

Jun 20, 2003

viewsIcon

389862

downloadIcon

10014

Code that exports a whole DataGrid into an Excel file.

Introduction

This sample demonstrates "How to export the whole DataGrid into an Excel file".

If you are looking for an easy way to export your DataGrid into an Excel file, then you have the solution now.

HTML encode an entire DataGrid. The code iterates through each cell in the table row, ensuring that all the text being displayed is HTML encoded, irrespective of whether they are just plain text, buttons, hyperlinks, multiple controls etc.

Include this code in your application/project and use it anywhere you want. This code takes just one parameter, the DataGrid object itself. Here is a sample calling code to use this code:

private void ExportLinkButton_Click(object sender, System.EventArgs e)
{
  string strTitle = “put the grid title here”;
  new DataGridExcelExporter(this.YourGridName , this.Page).Export(strTitle);
}

where,

  • strTitle is the title of the DataGrid.
  • DataGridExcelExporter is the name of main class.
  • this.YourGridName is the DataGrid object.
  • this.Page is the current Page object.

All you need to pass is your DataGrid object and a sweet title for the grid, and rest is taken care by this code. After all, take a look at the code, it's pretty self explanatory.

Pre-requisite: Microsoft Excel 97 or above should be installed on the client machine in order to make this function work.