Code Snippet: Export DataGridView To Excel With Columns

by Prashant 26. January 2011 01:12

This is among one of the best code snippet I have and using since long to export the datagridview to excel. The best part of this code snippet is that it just don't uses the excel interop, so you need not to worry about the Office version or PIAs installed at user's machine. What actualy is needed is just a Reflection namespace - System.Reflection and it will bind the data to the instance of the excel application.

 

private void Export2Excel(DataGridView datagridview, bool captions)
{
    if (datagridview.ColumnCount > 0)
    {
        string[] strArray = new string[datagridview.ColumnCount];
        string[] strArray2 = new string[datagridview.ColumnCount];
        int num = 0;
        int index = 0;
        int num3 = 0;
        for (index = 0; index < datagridview.ColumnCount; index++)
        {
            strArray[index] = datagridview.Rows[0].Cells[index].OwningColumn.Name.ToString();
            if ((num > 0) && ((index % num) == 0))
            {
                num = 0;
            }
            num3 = index / 0x1a;
            if (num3 == 0)
            {
                num = index + 0x41;
                strArray2[index] = Convert.ToString((char)num);
            }
            else
            {
                int num4 = num3 + 0x40;
                num = (index % 0x1a) + 0x41;
                strArray2[index] = Convert.ToString((char)num4) + Convert.ToString((char)num);
            }
        }
        try
        {
            object obj7;
            object target = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
            object obj4 = target.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, target, null);
            object obj3 = obj4.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, obj4, null);
            object obj5 = obj3.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, obj3, null);
            object[] args = new object[] { 1 };
            object obj6 = obj5.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, obj5, args);
            if (captions)
            {
                index = 0;
                while (index < datagridview.ColumnCount)
                {
                    args = new object[] { strArray2[index] + "1", Missing.Value };
                    obj7 = obj6.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, obj6, args);
                    args = new object[] { strArray[index] };
                    obj7.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, obj7, args);
                    index++;
                }
            }
            for (num = 0; num < datagridview.RowCount; num++)
            {
                for (index = 0; index < datagridview.ColumnCount; index++)
                {
                    args = new object[] { strArray2[index] + Convert.ToString((int)(num + 2)), Missing.Value };
                    obj7 = obj6.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, obj6, args);
                    args = new object[] { datagridview.Rows[num].Cells[strArray[index]].Value.ToString() };
                    obj7.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, obj7, args);
                }
            }
            args = new object[] { true };
            target.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, target, args);
            target.GetType().InvokeMember("UserControl", BindingFlags.SetProperty, null, target, args);
        }
        catch (Exception exception)
        {
            MessageBox.Show(("Error: " + exception.Message) + " Line: " + exception.Source, "Error");
        }
      }
    }

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

C# | Code Snippets


Comments (5) -

thenndral
thenndral Korea
12/8/2011 12:27:33 AM #

Hai,

Thanks for a such a code.
I have a questions.

I'm using VS2010[WPF/C#], Can I use this code in my project?

thanks,
thenndral

Reply

prashant
prashant India
12/9/2011 5:20:28 AM #

I haven't tried that but maybe if you are using System.Windows.Forms.DataGridView control in your WPF project.

Reply

dblwhooper
dblwhooper Singapore
3/26/2012 9:59:53 PM #

Hi,

May i know the codes i need to call this function from an export to excel button in VS2010?

i tried something like this:
        private void exportexcelbtn_Click(object sender, EventArgs e)
        {
            this.Export2Excel(datagridview, captions);
        }

but it doesnt work. Sorry im a C# newbie :O

Reply

Prashant
Prashant India
3/27/2012 12:55:52 AM #

You are calling the method correctly, but you are not passing the parameters correctly.

The first parameter should be the Name of the DataGridView control. Yo can find the Name of the DataGridView in the properties window. Select datagridview and press F4 to get the properties window.

The second parameter accepts only boolean values ie. true and false. If you want the captions in the top of your exported excel sheet then pass true and if you don't want the captions then pass false.

Reply

dblwhooper
dblwhooper Singapore
3/27/2012 4:45:21 PM #

Thanks alot bro! It sorta work but now i encounter 'Error: Object Reference not set to an instance of an object. Line: Vending Machine.'
Dang.

Reply

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Visit blogadda.com to discover Indian blogs Computers Blogs

About Me

Name of authorPrashant Khandelwal.
Programmer and tech enthusiast. More...

Feeds Subscribe Twitter Facebook Google Plus Linked In Delicious

Badges

MVB

MVP Blog Badge.

HTML5 Powered with CSS3 / Styling, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage

Month List

Blog Stats

414,206 Hits

Adverts

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Creative Commons License