En la página:
<div id="divExport">
<asp:GridView ID="GVDatos" runat="server">
.
.
.
</asp:GridView>
</div>
<asp:Button ID="BExport" runat="server" Text="Exportar a Excel" OnClientClick="ExportDivDataToExcel()"/>
Script de cliente:
<script type="text/javascript">
function ExportDivDataToExcel() {
var html = $("#divExport")[0].children[0].innerHTML;
html = $.trim(html);
html = html.replace(/>/g, '>');
html = html.replace(/</g, '<');
$("input[id$='HdnValue']").val(html);
}
</script>
Código de servidor (VB.NET):
Private Sub BExport_Click(sender As Object, e As System.EventArgs) Handles BExport.Click
Dim html As String = HdnValue.Value
If html.Trim.Length = 0 Then
Exit Sub
End If
ExportarExcel(html, "Datos")
End Sub
Public Sub ExportarExcel(html As String, archivo As String)
html = html.Replace(">", ">")
html = html.Replace("<", "<")
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & archivo & "_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") & ".xls")
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.Output.Write(html)
HttpContext.Current.Response.End()
End Sub
Se debe tener en cuenta que este método no funciona cuando <asp:Button ID="BExport"> se encuentra dentro de un UpdatePanel.
