无法在c#按钮单击时生成excel文件

时间:2015-04-12 06:42:06

标签: c#

在我的项目中,当我点击一个按钮时,它应该生成excel文件,并在excel文件的第一行中间作为标题我应该得到"我的第一个excel文件"。当我尝试使用以下代码时,我无法得到它。任何想法?提前致谢

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();
        }

    }
}

1 个答案:

答案 0 :(得分:2)

您忘记将内容添加到响应中 -

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

同时将您的内容类型更改为 -

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

不使用StreamWriter而是使用StringWriter并像这样更改代码 -

       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();

要将内容加载到excel文件中,如果建议您使用数据加载数据集,则将网格视图与该数据集绑定,然后将gridview渲染为html,之后用该渲染的html填充响应,如下所示:

  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();