Friday, 25 May 2012

Save GridView to Excel Sheet on server's disk using ASP.Net


In this article I will explain how to save ASP.Net GridView control to server’s disk as Microsoft Excel Spreadsheet using ASP.Net.
HTML Markup
In the below HTML Markup I have a simple ASP.Net GridView Control and an ASP.Net Button for saving the GridView to Excel sheet on server’s disk.
<form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <br>
    <asp:Button ID="btnSave" runat="server" Text="Save to Excel" OnClick="btnSave_Click" />
</form>

Namespaces
You will need to import the following namespaces for this sample tow work.
C#
using System.Data;
using System.IO;
VB.Net
Imports System.Data
Imports System.IO

Binding the GridView
In the below code snippet I am binding the ASP.Net GridView control with a datatable.
C#
protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("City");
    dt.Rows.Add();
    dt.Rows.Add();
    dt.Rows.Add();
    dt.Rows[0]["Name"] = "John Smith";
    dt.Rows[0]["City"] = "California";
    dt.Rows[1]["Name"] = "Andrew Clark";
    dt.Rows[1]["City"] = "Tokio";
    dt.Rows[2]["Name"] = "Mitchell Doe";
    dt.Rows[2]["City"] = "Dubai";
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    Dim dt As New DataTable()
    dt.Columns.Add("Name")
    dt.Columns.Add("City")
    dt.Rows.Add()
    dt.Rows.Add()
    dt.Rows.Add()
    dt.Rows(0)("Name") = "John Smith"
    dt.Rows(0)("City") = "California"
    dt.Rows(1)("Name") = "Andrew Clark"
    dt.Rows(1)("City") = "Tokio"
    dt.Rows(2)("Name") = "Mitchell Doe"
    dt.Rows(2)("City") = "Dubai"
    GridView1.DataSource = dt
    GridView1.DataBind()
End Sub

Saving the ASP.Net GridView as Excel Spreadsheet on Server’s Disk
Once the GridView is bind with data we will now write the code to save it as Excel file on the server’s disk. Hence on the Click event handler of the Save button I have written the following code.
C#
protected void btnSave_Click(object sender, EventArgs e)
{
    string path = Server.MapPath("~/Sheets/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            StreamWriter writer = File.AppendText(path + "GridView.xls");
            GridView1.RenderControl(hw);
            writer.WriteLine(sw.ToString());
            writer.Close();
        }
    }
}
VB.Net
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
   Dim path As String = Server.MapPath("~/Sheets/")
   If Not Directory.Exists(path) Then
        Directory.CreateDirectory(path)
   End If
   Using sw As New StringWriter()
        Using hw As New HtmlTextWriter(sw)
            Dim writer As StreamWriter = File.AppendText(path & "GridView.xls")
            GridView1.RenderControl(hw)
            writer.WriteLine(sw.ToString())
            writer.Close()
        End Using
    End Using
End Sub

Above I am first checking whether the Directory where the excel needs to be saved exists, if not I create it and then I render the GridView as HTML and then save it to disk using StreamWriter class.
While exporting you might get the following error
Server Error in '/ASP.Net' Application.

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

Downloads
You can download the source code in VB.Net and C# using the download link provided below.
SaveGridViewAsExcelOnDisk.zip

No comments:

Post a Comment

Note: only a member of this blog may post a comment.