Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Export DataGrid to Excel

0.00/5 (No votes)
2 Mar 2005 3  
Easily export DataGrid data to Excel.

Export to Excel (Windows forms only)

This is basically the easiest way to export data from a DataGrid or DataSet to Excel.

I looked all over the Internet and could not find anything useful, only ASP.NET ways of exporting. You just need to add to Excel DLL your references. I have looked over the Internet for the easiest way of doing it and at the end ended up doing this. Just put the code where ever you want to call the event that export the Dataset or DataGrid to Excel.

Excel.ApplicationClass excel = new ApplicationClass();

excel.Application.Workbooks.Add(true); 
DataTable table = DATASETNAME.Tables[0];
int ColumnIndex=0; 
foreach(Datacolumn col in table.Columns)
{   
   ColumnIndex++;
   excel.Cells[1,ColumnIndex]=col.ColumnName;
} 
int rowIndex=0; 
foreach(DataRow row in table.Row) 
{         
    rowIndex++;       
    ColumnIndex=0;         
    foreach(DataColumn col in table.Columns)         
    {  
        ColumnIndex++;                
        excel.Cells[rowIndex+1,ColumnIndex]=row.Cells[col.ColumnName].Text;         
    }
} 
excel.Visible = true; 
Worksheet worksheet = (Worksheet)excel.ActiveSheet; 
worksheet.Activate();
)

I know its not the most difficult thing on the planet to make, but it can be useful to beginners.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here