从GV 中如何把数据导入Excel ??
在GV中把符合的数据读出来,然后在点击按钮导入Excel 如何做!!
大哥大姐帮帮忙,最好有代码,谢谢了!!
[解决办法]
弱弱的问一句:GV是什么捏?
[解决办法]
1.导出Excel的类文件
using System;
using System.Data;
using System.Configuration;
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;
/// <summary>
/// Excel的摘要说明
/// </summary>
public class Excel:System.Web.UI.Page
{
public Excel()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// Grid导出excel
/// </summary>
/// <param name="GridView">GridView</param>
/// <param name="System.Web.UI.Page page">page</param>
/// <returns></returns>
public static void GridToExcel(GridView gv,System.Web.UI.Page page)
{
//导出excel
page.Response.Clear();
page.Response.Buffer = true;
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.Charset = "";
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
page.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
page.Response.Write(sw.ToString());
page.Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
2.在含有GV的页面调用,比如将事件写在btOutExcel上,以gvZC为例,
添加引用: using System.IO;
#region 导出Excel需要的东东(这个必需加上,否则会出错,空着就行)
public override void VerifyRenderingInServerForm(Control control)
{
}
#endregion
#region 导出Excel文件按钮事件
protected void btOutExcel_Click(object sender, EventArgs e)
{
gvZC.AllowPaging = false;//如果您gridview分了页,请加此代码
gvZC.Columns[0].Visible = false;//如果您的gridview有按钮列或不想显示的列,请隐藏列。
//导出excel
ZiChanBSL b = new ZiChanBSL();
gvZC.DataSource = b.getZiChan();
gvZC.DataBind(); //初始初自定义的方法,调用您的绑定gridview的方法重新绑定一次gridview
Excel.GridToExcel(gvZC, this.Page);
}
#endregion
应该绝对能用了