导出gridview的数据到Excel中

前台代码

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:LinkButton ID="lbExcel" runat="server" onclick="lbExcel_Click">导出Excel</asp:LinkButton>
    <asp:GridView ID="gvwStudent" runat="server">
    </asp:GridView>
    </form>
   
</body>
</html>

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ControlClassspace;
using System.Text;
using System.IO;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gridViewBind();
        }
    }

//绑定gridView的函数

    public void gridViewBind()
    {
        string sqlText = @"SELECT * FROM Student";
        ControlClass controlClass = new ControlClass();
        controlClass.BindGridView(gvwStudent, sqlText);
    }

    protected void lbExcel_Click(object sender, EventArgs e)
    {
        Export("application/vnd.xls", "xx.xls");
    }

    //重写此方法,使没有包含在<from runat="server">中的客户端脚本

   //gridview中必须要重写此方法,但datagrid中不需要
    public override void VerifyRenderingInServerForm(Control control)
    {

        /*以确认在运行时为指定的ASP.NET 控件呈现HtmlForm 控件*/
    }
    /// <summary>
    /// 导出gridview函数,提出来的好处是可以放在公用函数中
    /// </summary>
    /// <param name="FileType"></param>
    /// <param name="FileName"></param>
    private void Export(string FileType,string FileName)
    {
        Response.Charset = "gb2312";//字体
        //解决中文乱码
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
        //the title of Excel
        Response.AddHeader("content-disposition", "attachment;filename="+HttpUtility.UrlEncode(FileName,Encoding.UTF8).ToString());
        //To sign the File type
        Response.ContentType = FileType;
        //提交后不回显,加快系统速度
        this.EnableViewState = false;
        //实现一个用于将信息写入字符串的 TextWriter。该信息存储在基础 StringBuilder 中。
        StringWriter tw = new StringWriter();
        //将标记字符和文本写入到 ASP.NET 服务器控件输出流。此类提供 ASP.NET 服务器控件在向客户端呈现标记时所使用的格式设置功能。
        HtmlTextWriter htw = new HtmlTextWriter(tw);
        //将服务器控件的内容输出到所提供的 HtmlTextWriter 对象中;如果已启用跟踪功能,则存储有关控件的跟踪信息。
        gvwStudent.RenderControl(htw);
        Response.Write(tw.ToString());
        Response.End();
        gvwStudent.AllowPaging = true;//导出后先取消分页,以便能将所有数据导出。
        gridViewBind();//再重新绑定一次数据
    }
}

原文地址:https://www.cnblogs.com/xiajf/p/1876087.html