日期:2014-05-17  浏览次数:20503 次

怎样将页面查询出的内容导入Excel中?
asp页面的DetailsView中显示某人的个人信息,怎样将这条信息输出到Excel中?

------解决方案--------------------
打开excel模板,赋值给单元格

------解决方案--------------------
探讨
我是说在asp页面放一个按钮,名叫导出,点击该按钮,DetailsView中的内容自动导入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.Collections.Generic;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.AllowPaging = true;
GridView1.PageSize = 2;
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
MyDataBind();
}

public void MyDataBind()
{
List<Student> list = new List<Student>();
list.Add(new Student("张三丰", 100, "武当"));
list.Add(new Student("张翠山", 30, "武当"));
list.Add(new Student("张无忌", 20, "冰火岛"));
list.Add(new Student("诸葛亮", 53, "五丈原"));
list.Add(new Student("司马懿", 61, "长安"));

GridView1.DataSource = list;
GridView1.DataBind();
}
protected void btnToExcel_Click(object sender, EventArgs e)
{
//清空输出流中的内容
Response.Clear();
//设置输出流的字符编码
Response.ContentEncoding = System.Text.Encoding.Default;
//设置http头信息,第一个参数是key,第二个参数是value,用于设置excel文件的名字
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
//定义写入器
StringWriter stringWrite = new StringWriter();
//用于将字符和标记写入到输出流中
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//禁止分页
GridView1.AllowPaging = false;
//重新绑定数据(将显示所有数据,不分页)
MyDataBind();
//将控件gridview1的内容输出到htmlwrite中
GridView1.RenderControl(htmlWrite);
//将写入器中的内容(也就是htmlwrite中的内容)发送到缓冲区
Response.Write(stringWrite.ToString());
//将缓冲区的内容发送到客户端
Response.End();
//启用分页
GridView1.AllowPaging = true;
//重新绑定数据后,将恢复到点击“导出”按钮之前的分页状态
MyDataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
MyDataBind();
}

public override void VerifyRenderingInServerForm(Control control)
{

}
}