asp.net中实现GridView中的数据导入到Excel中

看了一些书,也看了很多人的代码 得到了几个核心的东西 于是总结一下:
  sp.net中实现GridView中的数据导入到Excel中:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using BLL;

public partial class GridView导入到Excel : System.Web.UI.Page
{

    private string fileName = "Information.xls";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["LogStatus"] != "LoggedIn")
                Response.Redirect("用户登陆.aspx");
        }

        GridDataBinds();

    }

    public void GridDataBinds()
    {
        DataSet ds = new DataSet();

        BLL.UserControl user = new BLL.UserControl();
       
        ds = user.GetAllInfo(Convert.ToInt32(Session["UserLoID"]));

        GridView_display.DataSource = ds;

        GridView_display.DataBind();

    }

    public void ExportExcel()
    {
        Response.Clear();

        Response.AddHeader("Content-Disposition","attachment;filename="+fileName+"");

        Response.Charset = "";

        //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

        Response.ContentType = "application/ms-xml";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridDataBinds();

        GridView_display.AllowPaging = false;

        GridView_display.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();

        GridView_display.AllowPaging = true;

        GridDataBinds();
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
    protected void Button_export_Click(object sender, EventArgs e)
    {
        ExportExcel();
    }
}
然后导出可能出现乱码,因为汉字的原因,于是我们需要设置一下
Response.Charset = "GB2312";

Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

这两句是改变属性的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值