事实上网上有非常多关于Excel的样例,可是不是非常好,他们的代码没有非常全,读的起来还非常晦涩。经过这几天的摸索,最终能够完毕我想要导出报表Excel的效果了。以下是我的效果图。

一.前台的页面图

GridView的第一页的内容

GridView第二页的内容:

大家可能遇到这样的情况,就是这个时候导出Excel的时候,打开Excel的时候发现GridView的第二页的内容却没有导出到Excel表里面。事实上解决这样的情况,非常easy,仅仅要在导出之前,把Gridview的设置分页设置为Flase即可了。

以下是我导出Gridview里面的所有内容,打开Excel表例如以下:

这就能够导出所有的GridView里面的内容了,包含了GridView的第一页和第二页的内容。

二、实现的代码

1.前台的代码:

<div style=" margin:20px;">

        <asp:GridView ID="gvRecord" runat="server" AllowPaging="True" CellPadding="3" 


            AutoGenerateColumns="False"  BorderColor="White"

            BorderStyle="Ridge" BorderWidth="2px" BackColor="White" CellSpacing="1"


            GridLines="None" onprerender="gvRecord_PreRender"

            onpageindexchanged="gvRecord_PageIndexChanged"

            onpageindexchanging="gvRecord_PageIndexChanging" >

            <PagerSettings FirstPageText="Home Page" LastPageText="Last Page"

                NextPageText="Next" PreviousPageText="Previous" />

            <RowStyle  ForeColor="Black" BackColor="#E5F1FF" HorizontalAlign="Center" />

            <Columns>

                <asp:TemplateField HeaderText="Extension">

    

                    <ItemTemplate>

                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Extn") %>'></asp:Label>

                    </ItemTemplate>

                    <ItemStyle Width="200px" />

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Wake up time">

            

                    <ItemTemplate>

                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("CallTime") %>'></asp:Label>

                    </ItemTemplate>

                    <ItemStyle Width="300px" />

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Status">

 

                    <ItemTemplate>

                        <asp:Label ID="Label3" runat="server" Text='<%# getResult(Eval("Status").ToString()) %>'></asp:Label>

                    </ItemTemplate>

                    <ItemStyle Width="250px" />

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Call number">

      

                    <ItemTemplate>

                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("callcount") %>'></asp:Label>

                    </ItemTemplate>

                    <ItemStyle Width="150px" />

                </asp:TemplateField>

            </Columns>

            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />

            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />

            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="#C9E2FF" Font-Bold="True" ForeColor="#000000" />

        </asp:GridView>

       

        <p>

            <asp:Button ID="btnExcel" CssClass="button"  runat="server" Text="Statements

"

                onclick="btnExcel_Click" /></p>

    </div>

2.后台代码例如以下:

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using Model;

using DAL;

using System.Collections.Generic;

using System.IO;

public partial class _3C_CallManager_CallRecord : System.Web.UI.Page

{

    int selectFlag = 0;

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            bind();

        }

    }

public string getResult(string str)

    {

        if (str == "0")

            return "Haven't called";

        if (str == "1")

            return "check-out";

        if (str == "2")

            return "success";

        if (str == "3")

            return "fail";

        if (str == "4")

            return "dealing";

        if (str == "5")

            return "Artificial wake";

        else

            return "unkown";

}

    public void bind() {

        selectFlag = 0;

        gvRecord.DataSource = VgCallService.GetInfo();

        gvRecord.DataBind();

    }

    protected void btnExcel_Click(object sender, EventArgs e)

    {

        DateTime dt = System.DateTime.Now;

        string str = dt.ToString("yyyyMMddhhmmss");

        str = str + ".xls";

gvRecord.AllowPaging = false;

        if (selectFlag == 0)

            bind();

        if (selectFlag == 1)

            selectBind();

GridViewToExcel(gvRecord, "application/ms-excel", str);

// Export(gvRecord, "application/ms-excel", str);

}

/// <summary>

    /// 将网格数据导出到Excel

    /// </summary>

    /// <param name="ctrl">网格名称(如GridView1)</param>

    /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>

    /// <param name="FileName">要保存的文件名称</param>

    public static void GridViewToExcel(Control ctrl, string FileType, string FileName)

    {

        HttpContext.Current.Response.Charset = "GB2312";

        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码

        HttpContext.Current.Response.AppendHeader("Content-Disposition",

            "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());

        HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword


        ctrl.Page.EnableViewState = false;

        StringWriter tw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(tw);

        ctrl.RenderControl(hw);

        HttpContext.Current.Response.Write(tw.ToString());

        HttpContext.Current.Response.End();

    }

    /// <summary>

    /// ReLoad this VerifyRenderingInServerForm is neccessary

    /// </summary>

    /// <param name="control"></param>

public override void VerifyRenderingInServerForm(Control control)

    {

}

protected void gvRecord_PreRender(object sender, EventArgs e)

    {

        if(selectFlag==0)

            bind();

      }

    protected void gvRecord_PageIndexChanged(object sender, EventArgs e)

    {

}

    protected void gvRecord_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        this.gvRecord.PageIndex = e.NewPageIndex;

bind();

    }

}

注意问题说明:

1)前台页面<%@ Page Language="C#" EnableEventValidation="false"  AutoEventWireup="true" CodeFile="CallRecord.aspx.cs" Inherits="_3C_CallManager_CallRecord" %>注意加入EnableEventValidation="false",要不然会报错的。

2)GridView的绑定数据库的代码

gvRecord.DataSource = VgCallService.GetInfo();//VgCallService.GetInfo()是获取数据库的集合,我是封装好的,依据你们的获取的集合做不同的调整。

        gvRecord.DataBind();

3)点击GridView下一页的关键代码,在PageIndexChanging事件里面

this.gvRecord.PageIndex = e.NewPageIndex;  //注意这个不能少。

bind();

4)在导出Excel的button事件里面记得先gvRecord.AllowPaging = false;把GridView的分页取消之后,再调用GridViewToExcel方法。

5)以下的不可少。

public override void VerifyRenderingInServerForm(Control control)

    {

}

GridView导出Excel的超好样例的更多相关文章

  1. Asp.net Gridview导出Excel

    前台页面放一个GridView什么的就不说了,要注意的是在 <%@ Page Language="C#" AutoEventWireup="true" C ...

  2. C#实现GridView导出Excel

    using System.Data;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System. ...

  3. ASP.NET gridview导出excel,防止繁体产生有乱码的方式

    //1.先引用比如 : using System; using System.Collections.Generic; using System.Linq; using System.Web; usi ...

  4. GridView导出excel格式问题

    在导出的点击事件中,代码如下: //指定导出对应单元格为文本样式 string style = @"<style> .test { vnd.ms-excel.numberform ...

  5. C# GridView 导出Excel表

    出错1:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内解决方案:在后台文件中重载VerifyRenderingInServerForm方法,如 ...

  6. GridView导出Excel(中文乱码)

    public void OUTEXCEL(string items,string where) { DataSet ds = new StudentBLL().GetTable(items,where ...

  7. GridView导出Excel

    public void OUTEXCEL() { DataSet ds = new GW_T_DemandDAL().GetWzH(GetPersonInfoData(UserInfo), Reque ...

  8. GridView 导出Excel

    protected void btnExcel_Click(object sender, EventArgs e) { ) { ExportGridViewForUTF8(GridView1, Dat ...

  9. NPOI 导出excel数据超65535自动分表

    工作上遇到的问题,网上找了一些资料 整理了一个比较可行的解决方案. NPOI 大数据量分多个sheet导出 代码段 /// <summary> /// DataTable转换成Excel文 ...

随机推荐

  1. json序列化后日期如何变回来

    日期格式为 日期小于10的时候 占一位 比如 2019年9月1日 2015/9/1 function ChangeDateFormat(cellval) {           var date = ...

  2. Java 之 网络编程

    1.OSI模型 a.全称:开放系统互联 b.七层模型:应用层.表示层.会话层.传输层.网络层.数据链路层.物理层 c.注意:OSI模型 是所谓的 理论标准 2.TCP/IP模型 a.四层模型:应用层. ...

  3. 第 15 章 组合模式【Composite Pattern】

    以下内容出自:<<24种设计模式介绍与6大设计原则>> 大家在上学的时候应该都学过“数据结构”这门课程吧,还记得其中有一节叫“二叉树”吧,我们上 学那会儿这一章节是必考内容,左 ...

  4. Java多线程初学者指南(11):使用Synchronized块同步方法

    synchronized关键字有两种用法.第一种就是在<使用Synchronized关键字同步类方法>一文中所介绍的直接用在方法的定义中.另外一种就是synchronized块.我们不仅可 ...

  5. requirejs学习博客址分享

    1. http://blog.jobbole.com/30046/ 2. http://www.requirejs.cn/ 3. http://www.ruanyifeng.com/blog/2012 ...

  6. python学习之---函数进阶

    一,递归函数: 做程序应该都知道,在一个函数的内部还可以调用其它函数,这叫函数的调用,但是有一种特殊的情况,在一个函数内部对自身函数的调用,我们成这为函数的递归调用. 在此,使用一个家喻户晓的例子来演 ...

  7. bzoj 1964: hull 三维凸包 计算几何

    1964: hull 三维凸包 Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 54  Solved: 39[Submit][Status][Discuss ...

  8. nojs iis asp.net mvc

    http://blogs.msdn.com/b/scott_hanselman/archive/2011/11/29/window-iis-node-js.aspx http://www.hansel ...

  9. 如何解决C#编译中"csc不是内部或外部命令"的问题

    安装完 VisualStudio 2010编译环境后,是不能用命令行直接编译写好的csc文件的,如果不配置环境变量,在命令提示符(cmd)中编译扩展名为cs的文件,会出现错误提示“csc不是内部或外部 ...

  10. Library Cache Lookup

    Libraey Cache Data Access library cache是关于SQL语句的SGA中的一系列的链表, library cache是通过访问一系列的hash buckets,实现使用 ...