简体   繁体   中英

Gridview to Excel file - save output instead of showing it

I have this code below which takes my GridView, populates it, and generates and opens an Excel file with the griddata in my browser.

What if I want to save that file directly to my server or attach it to an email message, instead of the display prompt that automatically pops up.

Can I do that with small modifications to the script?

protected void btnExcelExport_Click(object sender, EventArgs e) 
{ 
    HtmlForm form = new HtmlForm(); 

    Response.Clear(); 
    Response.Buffer = true; 
    Response.Charset = ""; 
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", "Student.xls")); 
    Response.ContentType = "application/ms-excel"; 

    StringWriter sw = new StringWriter(); 
    HtmlTextWriter hw = new HtmlTextWriter(sw); 

    GridView1.AllowPaging = false; 
    BindGridDetails(GridView1); 

    form.Attributes["runat"] = "server"; 
    form.Controls.Add(GridView1); 
    this.Controls.Add(form); 
    form.RenderControl(hw); 

    string style = @"<!--mce:2-->"; 
    Response.Write(style); 
    Response.Output.Write(sw.ToString()); 
    Response.Flush(); 
    Response.End(); 
}

you can save your grid data as a Comma Separated Value file on the server and email or save it directly on your server. CSV files can be opened using Excel.

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