Danish Habib

Danish Habib

  • NA
  • 694
  • 245.7k

Exporting simple gridview to excel

Jun 8 2015 6:54 AM
I have below markup in .aspx  page 
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick = "ExportToExcel" />
and below code behind i am using it runs normally but does not show any exported file
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Using sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
'To Export all pages
grdUserReports.AllowPaging = False
Me.SearchReportUser()
grdUserReports.HeaderRow.BackColor = Color.White
For Each cell As TableCell In grdUserReports.HeaderRow.Cells
cell.BackColor = grdUserReports.HeaderStyle.BackColor
Next
For Each row As GridViewRow In grdUserReports.Rows
row.BackColor = Color.White
For Each cell As TableCell In row.Cells
If row.RowIndex Mod 2 = 0 Then
cell.BackColor = grdUserReports.AlternatingRowStyle.BackColor
Else
cell.BackColor = grdUserReports.RowStyle.BackColor
End If
cell.CssClass = "textmode"
Next
Next
grdUserReports.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
End Sub
 

Answers (4)