GridView或者直接从数据库里面查询出来,可以用下面的:
string FileName = Session["User"] + "" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"
Response.Charset = "GB2312"
Response.ContentEncoding = System.Text.Encoding.UTF8
Response.AppendHeader("Content-Disposition", "attachmentfilename="
+ HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString())
Response.ContentType = "application/vnd.ms-excel"
this.EnableViewState = false
StringWriter tw = new StringWriter()
HtmlTextWriter hw = new HtmlTextWriter(tw)
grdView.AllowPaging = false
BindView()
grdView.RenderControl(hw)
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/htmlcharset=utf-8\">")
Response.Write(tw.ToString())
Response.Write("</body></html>")
Response.End()
你自己修改修改就行了
下面这个函数你可以放在类中,随时拿来用, 这是一个讲OleDbDataReader导出EXCEL的函数, 三个参数,第一个是页面,默认是本页this, 第二个是OleDbDataReader,第三个是导出的文件名public void CreateExcel(System.Web.UI.Page Page, OleDbDataReader dr, string FileName)
{
HttpResponse resp
resp = Page.Response
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312")
resp.AppendHeader("Content-Disposition", "attachmentfilename=" + FileName)
string colHeaders = "", ls_item = ""
int i = 0
for (i = 0i <dr.FieldCount - 1i++)
{
colHeaders += dr.GetName(i).ToString() + "\t"
}
colHeaders += dr.GetName(i).ToString() + "\n"
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders)
//逐行处理数据
while (dr.Read())
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = 0i <dr.FieldCount - 1i++)
{
ls_item += dr[i].ToString() + "\t"
}
ls_item += dr[i].ToString() + "\n"
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item)
ls_item = ""
}
//写缓冲区中的数据到HTTP头文件中
resp.End()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)