Recent Posts

Monday, July 6, 2009

How to export data from an Asp net website to an Excel File?

In web sites it is pretty good to have a export button for the users to get the data in excel displayed in grid or gridview insted of printing them.

Those can be very useful for many reporting issues in an organisation.

Here i am explaining the function that will help to export data from the website to an excel or csv file and it is pretty easy.

Private Sub ExportData()

Dim dt As Data.DataTable
Dim Bl As New BLL
' Here I get all the data required to fill data table from my business layer
dt = Bl.GetDataForExport()
'Create a dummy GridView
Dim GridView1 As New GridView()
GridView1.AllowPaging = False
GridView1.DataSource = dt
Response.Buffer = True
Response.AddHeader("content-disposition", _
Response.Charset = ""
Response.ContentType = "application/"
Dim sw As New IO.StringWriter()
Dim hw As New HtmlTextWriter(sw)

For i As Integer = 0 To GridView1.Rows.Count - 1
'Apply text style to each Row
GridView1.Rows(i).Attributes.Add("class", "textmode")

'style to format numbers to string
Dim style As String = ""

Catch ex As Exception
strErr = ex.ToString()
dvMsg.InnerHtml = strErr
dvMsg.Visible = True
End Try
End Sub

Just fetch the data from your business layer and use the above function on click event of the control, it will work for you.

Related Posts by Categories

No comments:

Post a Comment