您的位置:首页 > 编程语言 > ASP

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

2008-07-28 10:13 597 查看
看了一些书,也看了很多人的代码 得到了几个核心的东西 于是总结一下:
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");

这两句是改变属性的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: