导出EXCEL

protected void Button1_Click(object sender, EventArgs e)//按钮
    {
        GridView ctl = this.GridView1;//页面控件
        //DataGrid1是你在窗体中拖放的控件
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        HttpContext.Current.Response.Charset = "UTF-8";

        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {

    }

 

方式2:

 

StringWriter sw = new StringWriter();
        sw.WriteLine("留言消息\t评论用户\t评论时间");

        for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
        {
            string strs = ds.Tables[0].Rows[i]["message"].ToString() + "\t" + ds.Tables[0].Rows[i]["UserName"].ToString() + "\t" + ds.Tables[0].Rows[i]["InsertTime"].ToString();
            sw.WriteLine(strs);
        }
        sw.Close();
        Response.AddHeader("Content-Disposition", "attachment; filename=Message.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = Encoding.GetEncoding("GB2312");
        Response.Write(sw);
        Response.End();

 

using System.Data.Common;
using System.IO;
using System.Text;

 

你可能感兴趣的:(导出Excel)