下载GridView(保存为Excel文件)

Posted 流浪的向日葵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下载GridView(保存为Excel文件)相关的知识,希望对你有一定的参考价值。

aspx页面前台:(使用用户控件)

 <uc1:DownExcel ID="DownExcel1" runat="server" />

aspx页面后台:

    protected void Page_Load(object sender, EventArgs e)
    {
      
            DownExcel1.myEvent += new EventHandler(BindGV);
            DownExcel1.sFileName = "门店扫码明细表";
            DownExcel1.GridViewName = "GVExcel";
     }

 

用户控件前台:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<script type="text/javascript" language="javascript">
    function showM() {
        $find("popu").show();
    }
</script>

<asp:Button ID="Button1" runat="server" Text="下载" Width="80px" BackColor="#0066FF"
    Font-Bold="True" ForeColor="White" OnClick="Button1_Click"  OnClientClick="showM()"/>
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button3"
    BehaviorID="popu" PopupControlID="panModalPopup" BackgroundCssClass="cssModalBackground"
    DropShadow="true" CancelControlID="Image3">
</cc1:ModalPopupExtender>
<asp:Panel ID="panModalPopup" runat="server" Style="display: none">
    <asp:Image ID="Image3" runat="server" ImageUrl="~/Content/Images/Loading1.gif" />
</asp:Panel>

 

 

用户控件后台:

添加引用: using System.Web.UI.WebControls;
                   using System.IO;

    public event EventHandler myEvent;
    public string sFileName;
    public string GridViewName;

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            GridView gv = (GridView)Parent.FindControl(GridViewName);
            Response.Clear();
            string fileName = sFileName;
            Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode(fileName + ".xls"));
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            if (myEvent != null)
                myEvent(this, EventArgs.Empty);

            gv.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


   

以上是关于下载GridView(保存为Excel文件)的主要内容,如果未能解决你的问题,请参考以下文章

devexpress girdview 转excel求助

python接口自动化22-下载文件(excel)

django 中下载文件与下载保存为excel

如何在没有消息的情况下保存/覆盖现有的 Excel 文件

将 GridView 导出到 Excel 2007

如何将我的 excel gridview 添加到我的 aspxgridview 并保存在 sql server 中?