I am using the following vb to export to excel from asp.net
Private Sub ExportToExcel(table As DataTable, name As String)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.ContentType = "application/ms-excel"
HttpContext.Current.Response.Write("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">")
HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=" + name + ".xls")
HttpContext.Current.Response.Charset = "utf-8"
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250")
HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>")
HttpContext.Current.Response.Write("<BR><BR><BR>")
HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " + "borderColor='#000000' cellSpacing='0' cellPadding='0' " + "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>")
Dim columnscount As Integer = table.Columns.Count
For j As Integer = 0 To columnscount - 1
HttpContext.Current.Response.Write("<Td>")
HttpContext.Current.Response.Write(table.Columns(j).ColumnName.ToString())
HttpContext.Current.Response.Write("</Td>")
Next
HttpContext.Current.Response.Write("</TR>")
For Each row As DataRow In table.Rows
HttpContext.Current.Response.Write("<TR>")
For i As Integer = 0 To table.Columns.Count - 1
HttpContext.Current.Response.Write("<Td>")
HttpContext.Current.Response.Write(row(i).ToString())
HttpContext.Current.Response.Write("</Td>")
Next
HttpContext.Current.Response.Write("</TR>")
Next
HttpContext.Current.Response.Write("</Table>")
HttpContext.Current.Response.Write("</font>")
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.[End]()
End Sub
In this code the datatable(table) contains the data you wish to export to excel and name being the file name of the excel file.
For your question using this code I would suggest running a select from the database to populate a Datatable with the desired information for the output and then run it through this code.
rather than exporting directly from the datagrid.
otherwise I would suggest adding hidden columns to the datagrid and using those to export if you are not able to run a stored procedure to get the desired export data