How to write some text to an excel file in c#

4.1k Views Asked by At

I am adding the grid table to the excel and adding a header to the excel.

     string subject = lbl_Subj.Text;
    Response.Clear();
    Response.Buffer = true;
    Response.ClearHeaders();
    Response.AddHeader("Cache-Control", "no-store, no-cache");        
    Response.AddHeader("content-disposition", "attachment;filename=" + subject + "-Status");
    Response.Charset = "";
    this.EnableViewState = false;    
    Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    Grid_UserTable.RenderControl(htmlWrite);        
    rptList.RenderControl(htmlWrite);       
    Response.Write(stringWrite.ToString());     
    Response.End();

How can I add some text to the excel, I want to add some string like

string add="this is the text I want to add to the excel";
4

There are 4 best solutions below

0
On

As long as you are on office 2007/2010, you can use Office Open XML - http://msdn.microsoft.com/en-us/office/ee358824

Regards, Nitin Rastogi

0
On

You can't use string/html writer because excel is binary.

You have to use the Excel PIA's to create an excel sheet.

http://msdn.microsoft.com/en-us/library/ff597926.aspx

0
On
hw.RenderBeginTag("strong");
hw.Write("this is the text I want to add to the excel" + DateTime.Now);
hw.RenderEndTag();

Let me know if you need any help..

0
On

Try Adding : htmlWrite.WriteLine(add);

  string subject = lbl_Subj.Text;
    Response.Clear();
    Response.Buffer = true;
    Response.ClearHeaders();
    Response.AddHeader("Cache-Control", "no-store, no-cache");        
    Response.AddHeader("content-disposition", "attachment;filename=" + subject + "-Status");
    Response.Charset = "";
    this.EnableViewState = false;    
    Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    htmlWrite.WriteLine(add);

    Grid_UserTable.RenderControl(htmlWrite);        
    rptList.RenderControl(htmlWrite);       
    Response.Write(stringWrite.ToString());     
    Response.End();