prashanti
prashanti

Reputation: 31

could not generate excel file on button click in c#

In my project when i click on a button it should generate excel file and in the middle of first line in excel file as a heading i should get as "my first excel file". I could not get it when i am trying with following code.Any ideas?. Thanks in advance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace listofdirectories
{
    public partial class ExportToExcel : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.ContentType = "application/ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=practise.xls");
            StreamWriter stw = new StreamWriter();
            HtmlTextWriter htw = new HtmlTextWriter(stw);
            stw.WriteLine("my first excel file");
            response.End();
        }

    }
}

Upvotes: 0

Views: 791

Answers (1)

Manik Arora
Manik Arora

Reputation: 4792

You forgot to add the content to the response like this-

response.Write(stw.ToString());
response.End();

Also change your content type to this -

response.ContentType = "application/vnd.ms-excel";

Instead of using StreamWriter use StringWriter and change your code like this-

       Response.Clear();  
       Response.ClearContent();  
       Response.ClearHeaders();  
       Response.Charset = "";  
       string FileName = "filename.xls";  
       StringWriter strwritter = new StringWriter();  
       HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);        
       Response.Cache.SetCacheability(HttpCacheability.NoCache);  
       Response.ContentType ="application/vnd.ms-excel";    
       Response.AddHeader("Content-Disposition","attachment;filename=" + FileName); 
       Response.Write(strwritter.ToString());  
       Response.End();

To load the content in to the excel file, if recommend that you load the dataset with the data, then bind a grid view with that dataset and render the gridview as html after that fill the response with that rendered html like this-

  GridView gv = new GridView();
  gv.DataSource = dataset; //Your datasource from database
  gv.DataBind();
  Response.ClearContent();
  Response.Buffer = true;
  Response.AddHeader("content-disposition", "attachment; filename=filename.xls");
  Response.ContentType = "application/vnd.ms-excel";
  Response.Charset = "";
  StringWriter sw = new StringWriter();
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  gv.RenderControl(htw);
  Response.Write(sw.ToString());
  Response.Flush();
  Response.End();

Upvotes: 2

Related Questions