Thursday, April 2, 2009

Export to Excel from DataGridView

Here I am explaining, how we can generate Excel file from the DataGridView.

Here I am using DataTable.WriteXML method generate the excel file.

Create a Window Forms Application and on the Form1 add following controls

  1. DataGridView
  2. Button and rename to “Generate Excel File”
  3. FolderBrowserControl

image

Now add following code in Form1_Load Event, in following code I am creating a DataAdapter to get the data from data base and assigning DataGridView’s DataSource.

image

And add following code in Button1_Click event, In following code I getting back the DataSource and converting it into DataTable and using DataTable’s WriteXML method I am generating Excel File.

image

Now we are ready with our code just Build, Run and Test

image

Hope This Helps.

Tags: DataGridView, Excel, Export, C#, windows

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi, there is easier way to work with Excel using .NET. Check out GemBox spreadsheet component that is free for commercial use if you need less then 150 rows.

    ReplyDelete