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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • R与RStudio的详细安装教程(有每一步的详细教程!!!!)

    R与RStudio的详细安装教程(有每一步的详细教程!!!!)R与RStudio的详细安装教程(如果下面的博客没有能解决你的问题或者你还有其他关于计算机方面的问题需要咨询可以加博主QQ:1732501467)R是RStudio的前提,首先安装R,才能安装RStudio。安装R教程总共分为三步:一、下载R安装包二、安装R三、打开R安装RStudio,总共分为两步:一、安装RStudio二、测试RStudio是否安装成功R安装开始:一、下载R安装包1.下载网址:https://mirrors.tuna.tsinghua.edu.cn/CRAN/

    2022年6月26日
    48
  • 手机打开照相机_安卓11调用第三方相机

    手机打开照相机_安卓11调用第三方相机打开相机布局代码<Buttonandroid:id=”@+id/take_photo”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:layout_gravity=”center”android:text=”打开相机”/><Buttonandroid:id=”@+id/chose_photo”andro

    2022年9月22日
    2
  • CultureInfo中重要的InvariantCulture[通俗易懂]

    CultureInfo中重要的InvariantCulture[通俗易懂]CultureInfo简述CultureInfo类位于System.Globalization命名空间内,这个类和这个命名空间许多人都不了解也认为不需要太多了解,实际上,你写的程序中会经常间接得使用这些类。简单的说:当进行数字,日期时间,字符串匹配时,都会进行CultureInfo的操作,也就是不同的CultureInfo下,这些操作的结果可能会不一样。这里要介绍一下非常容易被忽视的In…

    2022年6月19日
    25
  • 「大数据干货」基于Hadoop的大数据平台实施——整体架构设计

    「大数据干货」基于Hadoop的大数据平台实施——整体架构设计大数据的热度在持续的升温 继云计算之后大数据成为又一大众所追捧的新星 我们暂不去讨论大数据到底是否适用于您的公司或组织 至少在互联网上已经被吹嘘成无所不能的超级战舰 大数据的热度在持续的升温 继云计算之后大数据成为又一大众所追捧的新星 我们暂不去讨论大数据到底是否适用于您的公司或组织 至少在互联网上已经被吹嘘成无所不能的超级战舰 好像一夜之间我们就从互联网时代跳跃进了大数据时代 关于到底什么是

    2025年12月4日
    2
  • maven打包常用命令总结

    maven打包常用命令总结maven打包常用命令总结基本命令介绍1、mvnclean2、mvncompile3、mvnpackage4、mvninstall5、mvndeploy生产环境打包举例1、生产环境根据源码构建项目:2、可用用到的其他mvn参数介绍:开发过程中常见以下几个命令,这些命令执行后程序究竟发生了什么变化?生产环境如果使用shell脚本配置jenkins构建项目,如何使用命令呢?下面介绍一下我常…

    2022年6月4日
    49
  • linux安装mysql8.0.16_mysql安装配置教程

    linux安装mysql8.0.16_mysql安装配置教程1.在/use/local下创建mysql文件夹mkdirmysql2.切换到mysql文件夹下cdmysql3.下载mysqlwgethttps://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz也可以直接在官方下载最新版本https://dev.mysql.com/downloads/mysql/选择linux4.解压mysqltar-zx……..

    2022年10月13日
    2

发表回复

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

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