GridView导出Excel的超好样例「建议收藏」

GridView导出Excel的超好样例「建议收藏」事实上网上有非常多关于Excel的样例,可是不是非常好,他们的代码没有非常全,读的起来还非常晦涩。经过这几天的摸索,最终能够完毕我想要导出报表Excel的效果了。以下是我的效果图。一.前台的页面图Gr

大家好,又见面了,我是你们的朋友全栈君。

 

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

一.前台的页面图

GridView的第一页的内容

GridView导出Excel的超好样例「建议收藏」

GridView第二页的内容:

GridView导出Excel的超好样例「建议收藏」

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

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

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)
    {

    }

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154869.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 【Python】python文件打开方式详解——a、a+、r+、w+、rb、rt区别[通俗易懂]

    【Python】python文件打开方式详解——a、a+、r+、w+、rb、rt区别[通俗易懂]第一步排除文件打开方式错误:r只读,r+读写,不创建w新建只写,w+新建读写,二者都会将文件内容清零(以w方式打开,不能读出。w+可读写)w+与r+区别:r+:可读可写,若文件不存在,报错;w+:可读可写,若文件不存在,创建r+与a+区别:fd=open(“1.txt”,’w+’)fd.write(‘123’)fd=open(“1.txt”,’r…

    2022年7月13日
    15
  • Python OpenCV findContours()函数与drawContours()函数用法

    Python OpenCV findContours()函数与drawContours()函数用法我用的Python3.6,OpenCV3.4。Python3.x与2.x语法不一样,OpenCV2.x与3.x也不一样。看之前得清楚自己用的啥。本文说白了就是个简单的查找轮廓,并且绘制轮廓。简单说一下这俩个函数用法。函数cv2.findContours()有三个参数。第一个是输入图像,第二个是轮廓检索模式,第三个是轮廓近似方法。而返回值根据OpenCV版本不同也不一样,但这俩个版本都会返回…

    2025年7月25日
    2
  • linux命令行与shell脚本编程大全和鸟哥的私房菜_linux进入命令行

    linux命令行与shell脚本编程大全和鸟哥的私房菜_linux进入命令行一、基本bashshell命令创建文件:touch链接文件:符号链接:是一个实实在在的文件,两个通过符号链接在一起的文件,彼此的内容并不相同。使用ln-s命令。硬链接:会创建独立的虚拟文件,其中包含了原始文件的信息及位置。但他们从根本上而言是同一个文件。原始文件必须事先存在,使用ln命令。查看文件类型:file查看整个文件:cat,more,less…

    2022年9月1日
    4
  • java 图片加密

    java 图片加密首先,了解下异或操作^,对一个数进行两次异或操作得到原数值。publicclassIOTest{ publicstaticvoidmain(String[]args){ inti=3; System.out.println(i^123);//120 System.out.println(i^123^123);//3 }}将一张图片进…

    2022年6月21日
    32
  • lua中的weak table及内存回收collectgarbage

    弱表(weaktable)是一个很有意思的东西,像C++/Java等语言是没有的。弱表的定义是:Aweaktableisatablewhoseelementsareweakreferences,元素为弱引用的表就叫弱表。有弱引用那么也就有强引用,有引用那么也就有非引用。我们先要厘这些基本概念:变量、值、类型、对象。(1)变量与值:Lua是一个dynamicallyty

    2022年4月7日
    95
  • 送学计算机男生什么礼物好,【十大男生喜欢的礼物】男生渴望收到什么礼物_主妇网…「建议收藏」

    送学计算机男生什么礼物好,【十大男生喜欢的礼物】男生渴望收到什么礼物_主妇网…「建议收藏」下周就是一年一度的西方情人节了,有恋人的都已经在想购买什么礼物给自己的爱人了。有心上人的也想着是不是要在情人节表白,想要让自己的男友开心,就一定要想好有什么礼物可以送给对方啦!小编整理了男生最渴望收到的礼物排行榜,希望能够给你一些启发哦!一、钱包钱包对于男人而言是为数不多的几件装饰品之一,而且也非常的实用,不论对方是不是已经有钱包了,你还是可以买一个给他。让对方在日常生活中拿出钱包就想起了你,而且…

    2022年7月25日
    10

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号