Download specific controls to word document in ASP.Net

Last Reply one year ago By dharmendr

Posted one year ago

How  to download only specific controles into word document in asp.net

Ex : I am having lable,text box etc., Every control was server side controle. Then how to download word document by applying hont sizes and styles

Posted one year ago Modified on one year ago

Hi saikumar,

To export specific controls you need to place the controls that you want to export inside a div or panel. Then export the panel to control instead of complete page.

Check this example. Now please take its reference and correct your code.

HTML

<div>
    <asp:Label ID="Label1" Text="Test Label" runat="server" />
    <asp:TextBox runat="server" Text="Test" />
    <br />
    <br />
    <asp:Panel runat="server" ID="pnlExport">
        <table border="1" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtName" />
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtAge" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    <br />
    <br />
    <asp:Button Text="Export" runat="server" OnClick="Export" />
</div>

C#

protected void Export(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/msword";
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
    pnlExport.RenderControl(htmlTextWriter);
    Response.Write(stringWriter.ToString());
    Response.End();
}


public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

VB.Net

Protected Sub Export(ByVal sender As Object, ByVal e As EventArgs)
    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/msword"
    Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter()
    Dim htmlTextWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
    pnlExport.RenderControl(htmlTextWriter)
    Response.Write(stringWriter.ToString())
    Response.End()
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    ' Verifies that the control is rendered 
End Sub

Screenshot

Page

After export to word document