About GridView Data To Excel C#

This Article will show on how to Transfer the GridView Data to Excel.

1. Suppose We have Data in GridView. Code Below will show on how to Load a Data in GridView.

//A sql query to get data from database
string sSQL = "Select * from TableName";

//Set DataTable
DataTable dt = new DataTable();

//Set SqlConnection
//yourconnectionstring ===> the sample of this string:Data Source=testserver;Initial Catalog=sampledatabase;User ID=sa;Password=sa
SqlConnection conn = New SqlConnection("yourconnectionstring");

//Set Command and DataAdapter and fill DataAdapter
SqlCommand cmd = new Sqlcommand(sSQL,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);

//This Session("LoadGrid") we will use it in excel
Session("LoadGrid") = dt;

//Datasource of your Grid and Bind it.
GridView1.DataSource = Session("LoadGrid");

2. Suppose we have Download Button to Excel. In the event of this button copy and paste the code Below.

Response.Write("As of " & Date.Now.ToLongDateString & "
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=FILENAME OF YOUR REPORT_" & Date.Now.ToString("(MM dd yyyy)") & ".xls")

'Prepare to export the DataGrid
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New HtmlTextWriter(oStringWriter)

Dim dgExport As New GridView
dgExport.DataSource = Session("LoadGrid")

dgExport.RowStyle.VerticalAlign = VerticalAlign.Top
dgExport.HeaderRow.Style.Value = "background-color: #00acc0; color: #fff;"
dgExport.Style.Value = "font-family: Verdana;"

'Use the DataGrid control to add the details

'Finish the Excel spreadsheet and send the response


Quick Info: http://dotnetspider.com/sites/450/Forum-914-GridView-To-Excel.aspx

Reference: http://dotnetspider.com/sites/450/Forum-914-GridView-To-Excel.aspx


Guest Author: Gerdoh01 May 2012

Bobby, fixed that issue the presentation slouhd now available for download from slideshare.Net under a creative commons license. Good point paul, thanks! I actually didn't talk about affinities but of course there's only so much you can cram into 30 minutes ;) on that slide i added the direct equivalent for as3 within parentheses but you can use certain other as3 data types as described in the livedocs you pointed out which are then ultimately treated as one of those basic storage types in sqlite.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: