下载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; } }
凡事预则立,不预则废。

浙公网安备 33010602011771号