Click here to Skip to main content
Licence CPOL
First Posted 5 Jan 2009
Views 99,859
Bookmarked 51 times

Exporting a DataGridView to Excel in .NET 2.0 (C# code)

By | 5 Jan 2009 | Article
This article explains how to export the contents of a .NET Datagridview control to an excel file

Introduction

Hi everyone! In this article I would be telling you how to export the contents of a .NET 2.0 DataGridView control to an excel file. This is a requirement often in many projects as users may want to save some data generated in applications for future reference. And as most other things .NET makes it really easy for the programmers.

Background

Most Microsoft Office products such as Word, Outlook etc are available to a .NET programmer as classes. Similarly Excel is also available as an Application class. To use it

  1. Add a reference to the ‘Microsoft Office 11.0 Object Library’ to your project from COM components.
  2. Create an object of the ApplicationClass in the Excel namespace
Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();

Excel application calls an excel file as a WorkBook. To export data to an excel file we need to create a new workbook in the application that is just created. Also more than one workbook can be opened in the application at a time (there is a collection called WorkBooks in the Excel application object). Only one of them will be the ActiveWorkBook (which can be access by the ActiveWorkBook property of the object). All the workbook related operations done to the application object will be directed to the ActiveWorkBook. We will need only one workbook. So that, by default, will be the ActiveWorkBook.

Using the Code

  1. Add a new workbook to the object of the Application class. The parameter to the Add method below is the name of the workbook. We are going to provide the name later (while saving the workbok). So Type.Missing can be used here. ExcelApp.Application.Workbooks.Add(Type.Missing);

    This is the stage where you can set general properties of the workbook. For example we can set the width of all the columns of the Workbook if you are not happy with the default column width.

  2. Change properties of the Workbook
    ExcelApp.Columns.ColumnWidth = 30;

    Next step is to copy the contents of the DataGridView to the Excel workbook. The cells of the WorkBook in the Excel application object can be accessed like a matrix. But one thing that you have to be careful about is that here the row and column numbering starts from 1. If you start from 0 you will get some weird exceptions. Iterate through each cell of the DataGridView object and copy the contents to the cells of the Excel Application Object (which goes to its active work book).

  3. Copy the contents of the DataGridView object to the cells of the Excel Application object. In the code below ReportDataGrodView is the name of my DataGridView object.
    for (int i = 0; i < ReportDataGridView.Rows.Count; i++)
    {
        DataGridViewRow row = ReportDataGridView.Rows[i];
        for(int j=0; j< row.Cells.Count; j++)
        {
            ExcelApp.Cells[i+1, j+1] = row.Cells[j].ToString();
        }
    }

    Then we have to save the workbook. There are 3 functions provided for that. Save, SaveAs and SaveCopyAs. I am using SaveCopyAs since I know that this is a new file generated and it cannot exist before. Probe on the other functions if you have a different requirement.

  4. Save the workbook at any suitable location. In the code below FileName is a string representing full path to the name of the file. This can be obtained from a SaveFileDialog if you want.
    ExcelApp.ActiveWorkbook.SaveCopyAs(FileName);
    ExcelApp.ActiveWorkbook.Saved = true;

Finally you have to close the Excel Application to free up the resources.

Exit the Excel Application and free up the resources

ExcelApp.Quit();

Summary

I have given below the summary of the seven steps required.

  1. Add a reference to the ‘Microsoft Office 11.0 Object Library’ to your project from COM components.
  2. Create an object of the ApplicationClass in the Excel namespace
    Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
  3. Add a new workbook to the object of the Application class. The parameter to the Add method below is the name of the workbook. We are going to provide the name later (while saving the file). So Type.Missing can be used here.
    ExcelApp.Application.Workbooks.Add(Type.Missing);
  4. Change properties of the Workbook
    ExcelApp.Columns.ColumnWidth = 30;
  5. Copy the contents of the DataGridView object to the cells of the Excel Application object. In the code below ReportDataGrodView is the name of my DataGridView object.
    for (int i = 0; i < ReportDataGridView.Rows.Count; i++)
    {
        DataGridViewRow row = ReportDataGridView.Rows[i];
        for(int j=0; j< row.Cells.Count; j++)
        {
            ExcelApp.Cells[i+1, j+1] = row.Cells[j].ToString();
        }
    }
  6. Save the workbook at any suitable location. In the code below FileName is a string representing full path to the name of the file. This can be obtained from a SaveFileDialog if you want.
    ExcelApp.ActiveWorkbook.SaveCopyAs(FileName);
    ExcelApp.ActiveWorkbook.Saved = true;
  7. Exit the Excel Application and free up the resources
    ExcelApp.Quit();

History

5/1/2009 - Created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Geek13



India India

Member

Eat, Sleep and Drink Code!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionDatagrid View to Excel Format Pinmembersanatmondal22:25 3 Apr '12  
SuggestionDon't use ApplicationClass (from Microsoft MSDN) PinmemberMember 205250417:32 20 Nov '11  
QuestionDatagridview to Excel.....using error (again) PinmemberPDTUM8:21 22 Aug '11  
QuestionMicrosoft Office 11.0 Object Libary PinmemberBoosh11:17 30 Jun '11  
GeneralData Transfer PinmemberFayazSurosh19:23 16 Apr '11  
GeneralRe: Data Transfer PinmemberDaveTheCaver17:13 22 Aug '11  
GeneralMy vote of 5 PinmemberZZ014717:49 3 Dec '10  
QuestionASP.NET or Winforms? PinmemberCode4Life0116:02 24 Aug '10  
Generalvery usefull Pinmemberjonesberyl21:54 17 Aug '10  
Generalvery well description! thank you Pinmemberpclion21:08 10 Jun '10  
GeneralUna correccion Pinmemberfquaino14:51 8 Apr '10  
GeneralError in code: "Old format or invalid type library" PinmemberH.R0:27 17 Jan '10  
GeneralRe: Error in code: "Old format or invalid type library" Pinmemberreborn070517:25 2 Jul '10  
GeneralRe: Error in code: "Old format or invalid type library" Pinmemberzvi1234670:46 20 Sep '10  
GeneralRe: Error in code: "Old format or invalid type library" Pinmembersmah118:14 11 Mar '11  
Generalgiving it a 4 PinmemberNightJammer7:11 7 Sep '09  
QuestionTwo workbooks open PinmemberHardus Lombaard21:57 28 Jul '09  
AnswerRe: Two workbooks open PinmemberGeek1320:38 30 Jul '09  
GeneralNice article, but a couple of suggestions... PinmemberSengo9:16 15 Jul '09  
General‘Microsoft Office 11.0 Object Library’ Pinmemberkim macintyre10:25 8 Jun '09  
GeneralRe: ‘Microsoft Office 11.0 Object Library’ PinmemberGeek1321:13 9 Jun '09  
GeneralRe: ‘Microsoft Office 11.0 Object Library’ Pinmembersmah118:09 11 Mar '11  
QuestionRe: ‘Microsoft Office 11.0 Object Library’ PinmemberBoosh19:15 18 Jun '11  
GeneralToo Slow PinmemberNouman Bhatti23:36 22 May '09  
GeneralRe: Too Slow PinmemberPeterMoon14:29 24 May '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 5 Jan 2009
Article Copyright 2009 by Geek13
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid