Microsoft has done a wonderful job of creating an extensible framework especially for ASP.NET by creating various server controls. This article is about extending ASP.NET button control and adding your own functionality for ONE CLICK exporting from ASP.NET page.
There are various ways one can export data using ASP.NET. Usually done by coding a separate page and adding various HTTP headers and responses. (Refer: http://support.microsoft.com/default.aspx?scid=kb;EN-US;317719).
Like me, most of us believe in reuse. The export functionality can be achieved by reusing same page for various projects either by passing DATASET from the parent page or reconnecting to the data source on the landing page and manipulating response object.
You may wonder why I call it ONE CLICK EXPORT, 'cause this control doesn't require intermediate page for exporting the data. Just drag the export button control on ASPX page or USER control and set its properties at design time or runtime to hook dataview. Yup, That’s it, no more hassles of dealing to investigate HTTP hearders, MIME types or encodings.
‘ASPX page [Design time]
…
…
<pnwc:ExportButton id="btnExcel" runat="server" Separator="TAB" Text="Export to Excel" FileNameToExport="Books.xls" BackColor="#E0E0E0"></pnwc:ExportButton>
….
….
‘Code Behind [Run time]
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds as dataset=filldataset()
dgBooks.DataSource = ds.Tables("Books")
dgBooks.DataBind()
'Set Export button properties
btnExcel.Dataview = ds.Tables("Books").DefaultView
btnExcel.FileNameToExport = "Books.xls"
btnExcel.ExportType = PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
btnExcel.Separator = PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB
End Sub
[Note: The Export button properties can either be set at Design time and/or Run time].
btnExcel.ExportType
= PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
btnExcel.Separator =
PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB
The source code is provided with the sample project to test out the solution.
Check out my .NET spot at http://prashantnayak.freeservers.com for more to discover.