Export to Excel from a Widget

Jun 11, 2008 at 9:42 PM
I have an image button on one of my widgets where I would like to export a datatable from the widget to Excel. I've listed the code I'm using. The DataGrid gets rendered properly to the HtmlTextWriter and has all the data from the DataTable, etc.  When I click the ImageButton1, an asynchronous postback occurs,  but the prompt to actually save the MyFile.xls file never appears in the browser. Any help would be appreciated.

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        DataTable table = getDataTable();
        ExportDataSetToExcel(table);
    }
    private void ExportDataSetToExcel(DataTable dt)
    {
        Response.Clear();
        Response.ContentType = "application/vnd.excel";
        Response.Charset = "";
        Response.AddHeader("content-disposition", "attachment; FileName=MyFile.xls");

        DataTable copyDataTable = dt.Copy();

        GridView dg = new GridView();
        dg.DataSource = copyDataTable;
        dg.DataBind();

        System.IO.StringWriter sw = new System.IO.StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        dg.RenderControl(htw);

        Response.Write(sw.ToString());
        Response.End();
    }

This is the code within the Widget's  ascx  file:
<div align="right">
    <asp:Panel ID="FooterPanel" runat="server" Visible="false">
        <table>
            <tr>
                <td align="center">
                    <asp:ImageButton ID="ImageButton1" runat="server"
                        ImageUrl="~/App_Themes/Default/excel_icon.gif" onclick="ImageButton1_Click"
                        Width="12px" />
                </td>
            </tr>
        </table>   
    </asp:Panel>
</div>


Jun 12, 2008 at 6:36 AM
Maybe you can add your control to updatepanel's PostBackTrigger.



<Triggers >
        <asp:PostBackTrigger  ControlID="" />
</Triggers>
Jun 12, 2008 at 1:24 PM
Yes, that works. I changed my FooterPanel to an update panel and added the trigger control as ImageButton1. Thanks rainmaker_ho. 
Also, I only make the FooterUpdatePanel visible when my DataTable has records.

Here's the code i changed in my .ascx page:

<div align="right">
    <asp:UpdatePanel ID="FooterUpdatePanel" runat="server" Visible="false">
        <Triggers >
            <asp:PostBackTrigger  ControlID="ImageButton1" />
        </Triggers>   
        <ContentTemplate>
        <table>
            <tr>
                <td align="center">
                    <asp:ImageButton ID="ImageButton1" runat="server"
                        ImageUrl="~/App_Themes/Default/excel_icon.gif" onclick="ImageButton1_Click"
                        Width="12px" />
                </td>
                <td>
                Save to Excel
                </td>                   
            </tr>
        </table>
        </ContentTemplate>   
    </asp:UpdatePanel>
</div>