| |||||||||||
IntroductionA good way to display data is to show it in a grid view. However, it becomes difficult to manipulate and filter large amounts of data in this way. Exporting data to an Excel file is a great solution for handling large amounts of data because Excel has many features -- such as sorting, searching and filtering -- that do not require you to write a single line of code. In this example, I will show:
Using the codeThis sample uses ASP.NET 2.0, C# and SQL Server 2005. I am using a simple form of the database table to avoid unnecessary overhead. Let us assume that we have a database named UniversityManager and that it has a table named Student. The structure of the table is as follows:
I am using the ASP.NET Collapse <asp:GridView ID="grdStudentMarks" runat="server" DataSourceID="dsStudentMarks"> <EmptyDataTemplate> No Data Found </EmptyDataTemplate> <RowStyle CssClass="ClsOddRow" /> <AlternatingRowStyle CssClass="ClsEvenRow" /> <HeaderStyle CssClass="ClsHeaderRow" /> </asp:GridView><asp:SqlDataSource ID="dsStudentMarks" runat="server" ConnectionString= "Data Source=.;Initial Catalog=UniversityManager;Integrated Security=True;" SelectCommand=" ( SELECT *FROM STUDENT ) "> </asp:SqlDataSource><asp:Button ID="btnExportFromDatagrid" runat="server" Text="Export From Grid" OnClick="btnExportFromDatagrid_Click" /><asp:Button ID="btnExportFromDataset" runat="server" Text="Export From Data set" /> When the ASP.NET page is rendered, protected void btnExportFromDatagrid_Click(object sender, EventArgs e) { ExportGridToExcel(grdStudentMarks, "StudentMarks.xls"); } public void ExportGridToExcel(GridView grdGridView, string fileName) { Response.Clear(); Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName)); Response.Charset = ""; Response.ContentType = "application/vnd.xls"; StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); grdGridView.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } When the button is clicked, we invoke the function The job is supposed to be done at this stage! However, were you to load the page and click the button, you would probably see the following error: Control 'grdStudentMarks' of type 'GridView' must be placed inside a form tag with runat=server. To resolve this error, you should override the public override void VerifyRenderingInServerForm(Control control) { } That's it! The data of the grid view will be exported to the Excel file, which should be saved to the desktop. However, there are some problems with this solution. First, if you use paging in your grid view, then only the data of an individual page will be exported instead of the data of whole grid. That means only those data which are rendered within the page will be exported. Second, if the data of the grid view is huge, you will probably get the following error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. This is a Timeout solutionI am going to use the Collapse protected void btnExportFromDataset_Click(object sender, EventArgs e){ ExportToExcel(dsStudentMarks, "StudentMarks");} public void ExportToExcel(SqlDataSource dataSrc, string fileName){ //Add Response header Response.Clear(); Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName)); Response.Charset = ""; Response.ContentType = "application/vnd.xls"; //GET Data From Database SqlConnection cn = new SqlConnection(dataSrc.ConnectionString); string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " "); SqlCommand cmd = new SqlCommand(query, cn); cmd.CommandTimeout = 999999 ; cmd.CommandType = CommandType.Text; try { cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); StringBuilder sb = new StringBuilder(); //Add Header for (int count = 0; count < dr.FieldCount; count++) { if (dr.GetName(count) != null) sb.Append(dr.GetName(count)); if (count < dr.FieldCount - 1) { sb.Append(","); } } Response.Write(sb.ToString() + "\n"); Response.Flush(); //Append Data while (dr.Read()) { sb = new StringBuilder(); for (int col = 0; col < dr.FieldCount - 1; col++) { if (!dr.IsDBNull(col)) sb.Append(dr.GetValue(col).ToString().Replace(",", " ")); sb.Append(","); } if (!dr.IsDBNull(dr.FieldCount - 1)) sb.Append(dr.GetValue( dr.FieldCount - 1).ToString().Replace(",", " ")); Response.Write(sb.ToString() + "\n"); Response.Flush(); } dr.Dispose(); } catch (Exception ex) { Response.Write(ex.Message); } finally { cmd.Connection.Close(); cn.Close(); } Response.End();} This solves the problem of downloading large amounts of data. The problem of the <httpRuntime maxRequestLength="209715" executionTimeout="3600" /> That's it! Points of interestSo, we have learned how to pull data from a database and show it in the grid view control. We have learned how to export data from grid view to an Excel file, how to export huge amounts of data from the data reader and how to export that data to an Excel file. I hope that this example helps you. Feel free to give me any suggestions regarding this article. Happy coding! HistoryThis demo was first uploaded on June 21st, 2007. About Fuad Bin Omar |
'ASP.NET' 카테고리의 다른 글
NET 2.0 에서 제공되는 TreeView사용법 (0) | 2007.09.04 |
---|---|
Ajax C#.NET simple chat: (0) | 2007.09.04 |
An ASP.NET DataGrid Freeze Header (0) | 2007.09.04 |
DataTableReader (0) | 2007.09.03 |
Using JavaScript Along with ASP.NET (0) | 2007.08.28 |