简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM