Encryption
Encryption

Reputation: 1897

Create file export and save from ASP.NET page

I have an ASP.NET web page that contains a grid view of user data. I need to take the data in the gridview, generate an excel file, and allow the user to save that excel file to their local machine.

What would be the best way to accomplish this in code? Would it be possible to display a file save dialogue and then create the file from the grid data after the user selects the directory and filename? I've accomplished this in software development but never dealt with it in web development.

Thanks

Upvotes: 0

Views: 2873

Answers (1)

Icarus
Icarus

Reputation: 63956

Most people tend to implement it like this:

protected void btnExportToExcel_Click(object sender, EventArgs e)    
{
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");

        Response.Charset = "";         
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();        
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);        
        Response.Write(stringWrite.ToString());
        Response.End();
}

Source.

Another alternative (the one I prefer) is to use EPPLus

Upvotes: 6

Related Questions