Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Office Development » Export DataGridView to Excel in C#

Export DataGridView to Excel in C#

This code example demonstrates how to export data from a DataGridView control to an Excel document using C#.

Author Rank :
Page Views : 22812
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


My application looks like Figure 1 where you can see I have some data in a DataGridView control on a Windows Forms application. I also have a Button called Export to Excel. When you click Export To Excel button, the application will export DataGridView data to an Excel document.

ExportDGVToExcelImg1.jpg
Figure 1

The Excel document will look like Figure 2.

ExportDGVToExcelImg2.jpg
Figure 2

Before you write code, you must add a reference to the Microsoft Excel object library.

Right click on your project and select Add Reference menu. After that go to COM tab and select and add Microsoft Excel 12.0 object library.

Now here is my Button click event handler where I create Excel object and document, get data from DataGridView and add rows and columns to the document.

Sample Code:

     private void button1_Click_1(object sender, EventArgs e)

        {

 

            // creating Excel Application

            Microsoft.Office.Interop.Excel._Application app  = new Microsoft.Office.Interop.Excel.Application();

 

 

            // creating new WorkBook within Excel application

            Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

           

 

            // creating new Excelsheet in workbook

             Microsoft.Office.Interop.Excel._Worksheet worksheet = null;                   

           

           // see the excel sheet behind the program

            app.Visible = true;

          

           // get the reference of first sheet. By default its name is Sheet1.

           // store its reference to worksheet

            worksheet = workbook.Sheets["Sheet1"];

            worksheet = workbook.ActiveSheet;

 

            // changing the name of active sheet

            worksheet.Name = "Exported from gridview";

 

           

            // storing header part in Excel

            for(int i=1;i<dataGridView1.Columns.Count+1;i++)

            {

    worksheet.Cells[1, i] = dataGridView1.Columns[i-1].HeaderText;

            }

 

 

 

            // storing Each row and column value to excel sheet

            for (int i=0; i < dataGridView1.Rows.Count-1 ; i++)

            {

                for(int j=0;j<dataGridView1.Columns.Count;j++)

                {

                    worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

                }

            }

 

 

            // save the application

            workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);

           

            // Exit from the application

          app.Quit();
        }

 

   

Note this part of code gets data from DataGridView and fills cells.

            // storing Each row and column value to excel sheet

            for (int i=0; i < dataGridView1.Rows.Count-1 ; i++)

            {

                for(int j=0;j<dataGridView1.Columns.Count;j++)

                {

                    worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

                }

            }

 

I have taken dataGridView1.Rows.Count-1, because in datagridview it contains empty row at the last. (See in the figure of datagridview.)

I hope you like this article. Feel free to post questions or comments.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Duong on Dec 02, 2010
// creating Excel Application
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            // creating new WorkBook within Excel application
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            // creating new Excelsheet in workbook
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            // see the excel sheet behind the program
            //Funny
            app.Visible = true;
            // get the reference of first sheet. By default its name is Sheet1.
            // store its reference to worksheet
            try
            {
                 //Fixed:(Microsoft.Office.Interop.Excel.Worksheet)
                worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
                worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
                // changing the name of active sheet
                worksheet.Name = "Exported from Ketoan";
                // storing header part in Excel
                for (int i = 1; i < DataGridView1.Columns.Count + 1; i++)
                {
                    worksheet.Cells[1, i] = DataGridView1.Columns[i - 1].HeaderText;
                }
                // storing Each row and column value to excel sheet
                for (int i = 0; i < DataGridView1.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < DataGridView1.Columns.Count; j++)
                    {
                        worksheet.Cells[i + 2, j + 1] = DataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                }

                // save the application
                string fileName = String.Empty;
                //SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                saveFileExcel.Filter = "Excel files |*.xls|All files (*.*)|*.*";
                saveFileExcel.FilterIndex = 2;
                saveFileExcel.RestoreDirectory = true;

                if (saveFileExcel.ShowDialog() == DialogResult.OK)
                {
                    fileName = saveFileExcel.FileName;
                    //Fixed-old code :11 para->add 1:Type.Missing
                    workbook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                }
                else
                    return;               

                // Exit from the application
                //app.Quit();
            }
            catch (System.Exception ex)
            {
                
            }
            finally
            {
                app.Quit();
                workbook = null;
                app = null;
            }
 [Top] Rate this article
 
 About the author
 
Hiren Soni
http://dotnetask.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Great piece of code by Filip On September 2, 2010
Hi,

thank you for this great piece of code.

I have also found another solution of your grid is bound to DataTable. Then you can easily, within just one method call export DataTable to Excel with this Excel .NET library.

Here is a sample Excel C# code:

// Create new ExcelFile.
var ef = new ExcelFile();

// Add new worksheet to the file.
var ws = ef.Worksheets.Add(dataTable.TableName);

// Insert the data from DataTable to the worksheet starting at cell "A1".
ws.InsertDataTable(dataTable, "A1", true);

// Save the file to XLS format.
ef.SaveXls("DataTable.xls");
Reply | Email | Modify 
thanks sir by nithya On November 26, 2010
 I am a beginner in this field  so i got a few error related to this article  . so please cleare my doubt .
 when i use this code like
worksheet = workbook.Sheets["Sheet1"];

          worksheet = workbook.ActiveSheet;
 i got Error        Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) 
 
 when i use save command  the error like it takes 11 argument. my big doubt is i used  sql datatatable to select query from table then i got
Error       'DataTable' is an ambiguous reference between 'System.Data.DataTable' and 'Microsoft.Office.Interop.Excel.DataTable'
 how i remove this error . its very urgent

          

Reply | Email | Modify 
somasekhar akiri by sekhar On February 21, 2011
nice article, it helps me alot
Reply | Email | Modify 
hi, by vishnuvardhan On March 11, 2011
I m beginer in this field, So i got some eror related to this article. That was name space error. Please help me to solve this error .Thanks in advance. my code is using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Excel = Microsoft.Office.Interop.Excel; namespace datagridview { public partial class Form1 : Form { int cntr = 0; OleDbConnection con =new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=E:\\datagridview\\db1.mdb"); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'db1DataSet.tokendetails' table. You can move, or remove it, as needed. this.tokendetailsTableAdapter.Fill(this.db1DataSet.tokendetails); } private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (cntr % 2 == 0) dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], ListSortDirection.Ascending); else dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], ListSortDirection.Descending); cntr++; } private void button4_Click(object sender, EventArgs e) { // creating Excel Application Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); // creating new WorkBook within Excel application Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); // creating new Excelsheet in workbook Microsoft.Office.Interop.Excel._Worksheet worksheet = null; // see the excel sheet behind the program //Funny app.Visible = true; // get the reference of first sheet. By default its name is Sheet1. // store its reference to worksheet try { //Fixed:(Microsoft.Office.Interop.Excel.Worksheet) worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"]; worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet; // changing the name of active sheet worksheet.Name = "Exported from Ketoan"; // storing header part in Excel for (int i = 1; i < dataGridView1 .Columns .Count + 1; i++) { worksheet.Cells[1, i] = dataGridView1 .Columns [i - 1].HeaderText; } // storing Each row and column value to excel sheet for (int i = 0; i < dataGridView1 .Rows .Count - 1; i++) { for (int j = 0; j < dataGridView1 .Columns .Count; j++) { worksheet.Cells[i + 2, j + 1] = dataGridView1 .Rows [i].Cells[j].Value.ToString(); } } // save the application string fileName = String.Empty; //SaveFileDialog saveFileDialog1 = new SaveFileDialog(); SaveFileDialog saveExcel = new saveExcel(); // SaveFileDialog saveFileExcel = new saveFileExcel(); saveExcel .Filter = "Excel files | *.xls|All files(*.*)|*.*"; saveExcel.FilterIndex = 2; saveExcel .RestoreDirectory = true; //saveFileExcel.Filter = "Excel files |*.xls|All files (*.*)|*.*"; //saveFileExcel.FilterIndex = 2; //saveFileExcel.RestoreDirectory = true; if (saveExcel .ShowDialog() == DialogResult.OK) { fileName = saveExcel .FileName; //Fixed-old code :11 para->add 1:Type.Missing workbook.SaveAs("export", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } else return; // Exit from the application //app.Quit(); } catch (System.Exception ex) { } finally { app.Quit(); workbook = null; app = null; } } } }
Reply | Email | Modify 
exporting datadrid from c# windows form to excel sheet by Suman On May 5, 2011
After adding reference to COM object as shown above........include using Excel = Microsoft.Office.Interop.Excel; and then just copy and paste this code....it surely works....i too tried Microsoft.Office.Interop.Excel.Application wapp; Microsoft.Office.Interop.Excel.Worksheet wsheet; Microsoft.Office.Interop.Excel.Workbook wbook; wapp = new Microsoft.Office.Interop.Excel.Application(); wapp.Visible = false; wbook = wapp.Workbooks.Add(true); wsheet = (Excel.Worksheet)wbook.ActiveSheet; try { //int iX; //int iY; int i; for (i = 0; i < this.dataGridView1.Columns.Count; i++) { wsheet.Cells[1, i + 1] = this.dataGridView1.Columns[i].HeaderText; //System.Drawing.FontStyle.Bold; } wsheet.get_Range(wsheet.Cells[1, 1], wsheet.Cells[1, i]).Font.Bold = true; for (i = 0; i < this.dataGridView1.Rows.Count; i++) { DataGridViewRow row = this.dataGridView1.Rows[i]; for (int j = 0; j < row.Cells.Count; j++) { DataGridViewCell cell = row.Cells[j]; try { wsheet.Cells[i + 2, j + 1] = (cell.Value == null) ? "" : cell.Value.ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } wapp.Visible = true; } catch (Exception ex1) { MessageBox.Show(ex1.Message); }
Reply | Email | Modify 
perfect!! by venice On June 20, 2011
it worked!... how about cell size and merging of cell...???
Reply | Email | Modify 
perfect!! by venice On June 20, 2011
it worked!... how about cell size and merging of cells...???
Reply | Email | Modify 
perfect!! by venice On June 20, 2011
it worked!... how about cell size and merging of cells...???
Reply | Email | Modify 
Re: perfect!! by Hiren On June 21, 2011
Please rewrite your problem in detail...
Reply | Email | Modify 
Re: Re: perfect!! by venice On June 21, 2011
I have already transferred the contents of datagridview to excel. Thanks to your code,,. Is there any way that I can change the cell size and by any chance merge cells in excel.. using c# ?? thanks!
Reply | Email | Modify 
Re: Re: Re: perfect!! by Hiren On June 22, 2011
// For height and width of cell worksheet.Range["A1"].ColumnWidth = 20; worksheet.Range["A1"].RowHeight = 50; // merge app.get_Range("A1:A3", "b1:b3").Merge();
Reply | Email | Modify 
Re: Re: Re: Re: perfect!! by venice On June 22, 2011
thanks!I know this is a lot... but is it possible to add image to excel even it is not from the datagridview?? lke from a picturebox...?,,, You're really a great help!
Reply | Email | Modify 
hey buddy this is manesh by manesh On November 10, 2011
one problem here is that in the above program where is the "saveFileExcel" declared Contents added by Duong on Dec 02, 2010 please give some clarity
Reply | Email | Modify 
Export DataGridView to Excel in C# by Sam On January 25, 2012
How can we save the data to the same excel worksheet and ignore duplicates in the excel worksheet?
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.