0

I am using Visual Studio 2015, Entity Framework 6 and C#.

I am trying to get my gridview to export to excel. I think I have everything, but when clicking the button my gridview disappears and nothing ever goes to a file.

My gridview is:

gvExOr

The Excel Export code is:

  public partial class _Default : Page
  {
    private void BindFiles()
    {
        DirectoryInfo di = new DirectoryInfo(tbPath.Text);
        gvExOr.DataSource = di.GetFiles();
        try {
            gvExOr.DataBind();
        }
        catch { }
    }
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        ExportToExcel();
    }
    //Export to Excel from a GridView
    protected void ExportToExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application / vnd.ms - excel";
        Response.AddHeader("content - disposition", "attachment; filename = MyFiles.xls");
        Response.Charset = "";
        this.EnableViewState = false;

        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 
        gvExOr.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End(); 
     }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }   
    protected void Page_Load(object sender, EventArgs e)
    {   
      BindFiles();
    }
  }

How do I get the gridview to export to excel?

Rojalin Sahoo
  • 1,025
  • 1
  • 7
  • 18
wiredlime2015
  • 123
  • 3
  • 15

1 Answers1

1

Looks like you used code from this post https://stackoverflow.com/a/10412559/5786449

I tried the example from that post and it works for me. The only difference I can see is in your Response.ContentType and Response.AddHeader. Try getting rid of the white spaces in those parameters:

Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");

One more thing, your code doesn't actually give you an Excel spreadsheet. It just writes out the GridView HTML markup. Many Excel programs are not expecting HTML in an XLS file and will throw an error when opening the file. If you want an actual Excel spreadsheet I would recommend looking into utilities like EPPlus http://epplus.codeplex.com/

Community
  • 1
  • 1
Kurorion
  • 108
  • 7