将 GridView 中的数据导出为 Excel 文件

假设在 .aspx 文件中,已有一个名为 GridView_Warehousing 的GridView控件,现在要加入将它导出为Excel文件的功能。

一、首先设置aspx页面EnableEventValidation="false",如下:

C# 代码:

<%@ Page Title="入库 - 嘉里大通诺基亚仓库管理系统" Language="C#" MasterPageFile="~/MasterPage/Operator.master" AutoEventWireup="true" CodeFile="Warehousing.aspx.cs" Inherits="Operator_Warehousing" EnableEventValidation="false" %>

二、在页面中加入一个按钮,如下:

C# 代码:

<asp:Button id="btnExport" runat="server" Text="以Excel文件格式导出" onclick="btnExport_Click" />

三、后台关键代码:

C# 代码:

    /// <summary>
    /// 以 Excel 文件格式导出 按钮按下事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "入仓储确认单.xls");
    }

    /// <summary>
    /// 以 Excel 文件格式导出
    /// </summary>
    /// <param name="fileType"></param>
    /// <param name="fileName"></param>
    private void Export(string fileType, string fileName)
    {
        // 以下三行可选,如果没有的话导出的只是当前页数据,没有其他页数据
        //this.GridView_Warehousing.AllowPaging = false;
        //this.GridView_Warehousing.AllowSorting = false;
        // 绑定 GridView

        // 导出时隐藏操作列
        this.GridView_Warehousing.Columns[0].Visible = false;
        // 隐藏分页行
        this.GridView_Warehousing.BottomPagerRow.Visible = false;
        Response.Clear();
        Response.Buffer = true;
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
        // 设置输出文件类型为excel文件
        Response.ContentType = "application/ms-excel";
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
        this.GridView_Warehousing.RenderControl(htmlTextWriter);
        Response.Output.Write(stringWriter.ToString());
        Response.Flush();
        Response.End();
    }

    /// <summary>
    /// 这个方法是配合导出 Excel 功能的,内容不用写
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

四、如果发现点击按钮出现 JavaScript 错误,则可能是由于页面中加入了 UpdatePanel 所致,如果是这个原因,就需要给 UpdatePanel 添加 Triggers 节点,如下:

C# 代码:

        <Triggers>
            <asp:PostBackTrigger ControlID="btnExport" />
        </Triggers>

 

Add comment

Loading