如何在c#中将一些文本写入excel文件

时间:2011-11-28 11:25:43

标签: c# htmltextwriter stringwriter

我将网格表添加到excel并向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();

如何向excel添加一些文本,我想添加一些像

这样的字符串
string add="this is the text I want to add to the excel";

4 个答案:

答案 0 :(得分:2)

尝试添加: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();

答案 1 :(得分:0)

只要您在2007/2010上班,就可以使用Office Open XML - http://msdn.microsoft.com/en-us/office/ee358824

此致 Nitin Rastogi

答案 2 :(得分:0)

你不能使用string / html writer,因为excel是二进制文件。

您必须使用Excel PIA来创建Excel工作表。

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

答案 3 :(得分:0)

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

如果您需要任何帮助,请告诉我。