代码改变世界

.net中将GridView中的部分内容或者全部内容导出到Excel中

2010-04-07 15:06  周国选  阅读(1664)  评论(0编辑  收藏  举报

1.以下是主要的导出为Excel格式的代码:

 

            Response.Clear();

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

            Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");//此处为了处理保存名避免乱码

            Response.Charset = "gb2312";

            Response.ContentType = "application/vnd.xls";

 

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

 

            GrantReleaseView.AllowPaging = false;//导出前先取消分页,以便能将所有数据导出。

            GrantReleaseInfoBLL.Bind(campusId, depId, year, pageSize, pageIndex, out pageCount, GrantReleaseView);//再重新绑定一次数据

 

            GrantReleaseView.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());

            Response.End();

 

            GrantReleaseView.AllowPaging = true;//导出后先取消分页,以便能将所有数据导出。

            GrantReleaseInfoBLL.Bind(campusId, depId, year, pageSize, pageIndex, out pageCount, GrantReleaseView);//再重新绑定一次数据

 

2.同时需要在代码中添加以下方法:重写一个空的VerifyRenderingInServerForm方法。

public override void VerifyRenderingInServerForm(Control control)

    {

            /*以确认在运行时为指定的ASP.NET 控件呈现HtmlForm 控件*/

    }

 

3.在页面的page属性中加入EnableEventValidation = "false" .如:

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation = "false" CodeFile="ExpertsList.aspx.cs" Inherits="ExpertsList" %>

 

4.要是需要是部分导出时:就将不需要的隐藏 方法如下:

 

            GrantReleaseView.Columns[0].Visible = true;

            GrantReleaseView.Columns[1].Visible = false;

            GrantReleaseView.Columns[GrantReleaseView.Columns.Count-1].Visible = false;

            GrantReleaseView.Columns[GrantReleaseView.Columns.Count-2].Visible = false;

 

   将指定的列导出时隐藏

 

5.在导出的Excel中添加序列号
当需要在Excel表中包括序列号时:应该在Gridview中添加序列号这一列,在显示的时候隐藏,在导出时显示,就OK

 

Gridview
竖着分:多个Column ()

横着分:row , row ()中又包含了多个cell 单元格.