Click here to Skip to main content
Click here to Skip to main content

Export DataGridView to Excel

By , 22 Nov 2012
 

Introduction

This is how to export a DataGridView to Excel.

Background

I had an application with an 8-tab window. Each window contained 1-3 DataGridViews.

Order from boss: Add export to Excel functionality!

The code

So I created an ExcelExporter class:

Option Explicit On
Option Strict On
Imports x = Microsoft.Office.Interop.Excel
Friend Class ExcelExporter

I recommend Option Strict On.

Option Strict Off (which unfortunately is the default) = Option Slow On (Dan Appleman). Do a disassembly and you will see.

Option Strict On also gives you intellisense.

Import Office Interop

I then created  a function : Export

Friend Function Export(ByRef dgv As DataGridView, ByVal Path As String) As Boolean

It takes a DataGridView and a path where to save the Excel file.

Since a DataGridView sometimes allows a user to rearrange the columns or allows the programmer to hide columns you have to get the columns by display index:

'get all visible columns in display index order
Dim ColNames As List(Of String) = (From col As DataGridViewColumn _
                                   In dgv.Columns.Cast(Of DataGridViewColumn)() _
                                   Where (col.Visible = True) _
                                   Order By col.DisplayIndex _
                                   Select col.Name).ToList

After that, if you want the column headers:

'get the headers
Dim colcount = 0
For Each s In ColNames
    colcount += 1
    xlWorkSheet.Cells(1, colcount) = dgv.Columns.Item(s).HeaderText
Next

And then, the rows and all their columns:

'get the values
For rowcount = 0 To dgv.Rows.Count - 1  'for each row
    colcount = 0
    For Each s In ColNames 'for each column
        colcount += 1
        xlWorkSheet.Cells(rowcount + 2, colcount) = dgv.Rows(rowcount).Cells(s).Value
        'xlWorkSheet.Cells(rowcount + 2, colcount) = dgv.Rows(rowcount).Cells(s).FormattedValue
    Next
Next

If you want the unformatted value: use Value

If you want the formatted value: use FormattedValue.

Using the code

Private Sub dgData_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
           Handles dgData0.MouseClick, dgData1.MouseClick, _
                   dgData3.MouseClick, dgData4.MouseClick
    If e.Button = MouseButtons.Right Then
        Dim dgData As DataGridView = DirectCast(sender, DataGridView)
        With SaveExcelFileDialog
            .Filter = "Excel|*.xlsx"
            .Title = "Save griddata in Excel"
            If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                Dim o As New ExcelExporter
                Dim b = o.Export(dgData, .FileName)
            End If
            .Dispose()
        End With
    End If
End Sub

License

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

About the Author

Michael Rosqvist
Web Developer
Sweden Sweden
Member
No Biography provided

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberRossMcPhee15 May '13 - 1:41 
GeneralMy vote of 1memberL3AP19 Feb '13 - 20:51 
QuestionHelp!memberL3AP19 Feb '13 - 20:13 
AnswerRe: Help!memberMichael Rosqvist19 Feb '13 - 22:20 
QuestionNice TutorialmemberVanlalruata4 Jan '13 - 3:52 
It is nice.....but some of the stuff are not available in C# Language!
 
Creating a Sheet, Workbook is fine.
 
            Workbook xlWorkBook;
            Worksheet xlWorkSheet;
            Range work_range = null;
            object misValue = System.Reflection.Missing.Value;
            Range chartRange;
            var xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.Visible=true;
            xlWorkBook = (Workbook)(xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
            xlWorkBook.SaveAs(path, XlFileFormat.xlWorkbookDefault, null, null, false, false, XlSaveAsAccessMode.xlExclusive,false, false, null, null, null);            
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);        
 
I added these lines of code. And it create the Spreedsheet and also I wrote you code after this...
 
 
            //Get Header
            int colcount = 0;
            foreach (string s in ColNames)
            {
                colcount += 1;
                xlWorkSheet.Cells[1, colcount] = dg.Columns[s].HeaderText; 
            }
 
            //Get Values
            //for each row
            for (int rowcount = 0; rowcount <= dg.Rows.Count - 1; rowcount++)
            {
                colcount = 0;
                //for each column
                foreach (string s in ColNames)
                {
                    colcount += 1;
                    xlWorkSheet.Cells[rowcount + 2, colcount] = dg.Rows[rowcount].Cells[s].Value;                    
                }
            }
 
Anyway thanks for your article.
 
Option Explicit On
Option Strict On
Friend Class ExcelExporter
 
These lines is really confusing for me to write in C#.
 
I don't know where to write the Option Strict On or Off. I don't even know what might be the alternative code for C# .....
 
Shucks | :-> Wink | ;-)
ZoSoft Network

AnswerRe: Nice TutorialmemberMichael Rosqvist19 Feb '13 - 22:18 
Questionplease helpmemberspacer21 Nov '12 - 0:46 
AnswerRe: please helpmemberMichael Rosqvist21 Nov '12 - 3:16 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 22 Nov 2012
Article Copyright 2012 by Michael Rosqvist
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid