1

I am new to .net. I have written a code to export a gridview into excel. the export works but instead of getting data of gridview I get tags in the exported document. Same case if I exported the gridview to docs. This is what exported file looks like

enter image description here

The GridView I have gets populated by a search query. Here is an excerpt of my code:

Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    MsgBox("Exporting")

    Response.Clear()
    Response.Buffer = True

    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
    Response.Charset = ""
    Response.ContentType = "application/vnd.ms-excel"

    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)

    gridviewID.AllowPaging = False
    gridviewID.DataSource = gvDataTable
    gridviewID.DataBind()
    gridviewID.RenderControl(hw)

    Response.Write(sw.ToString())
    Response.Flush()
    Response.End()

My GridView is not inside a Form tag as I already have a Form tag in my master page. This is how my GridView looks:

<asp:GridView ID="gridviewID" runat="server"
                        AutoGenerateColumns="False" onrowcommand="searchResultsGridView_RowCommand">
                        <Columns>
                            <asp:BoundField DataField="logNum" HeaderText="ID" ReadOnly="True" ItemStyle-CssClass="hideme" />

                            <asp:BoundField DataField="workIDName" HeaderText="work NAME"
                              SortExpression="workIDName" ReadOnly="True" />

                            <asp:BoundField DataField="LeadIdName" HeaderText=" LEAD"
                              SortExpression="LeadIdName" ReadOnly="True" />

                            <asp:BoundField DataField="Lead_Name2"// and a lot of fields till closing tags

I have placed verifyrendering function right after my page load. Placing this function right after export function wouldn't work. It would not let me export at all.

What could i be possibly doing wrong?

Blackwood
  • 4,504
  • 16
  • 32
  • 41
  • What does this mean "I get tags in the exported document"? What exactly is the error or problem? – IrishChieftain Mar 14 '18 at 22:31
  • 2
    The thing that you are doing wrong is that you are not exporting an excel file but a html page with an xlsx extension. Use a specialized libary like EPPlus. – VDWWD Mar 14 '18 at 22:31
  • Possible duplicate of [Import and Export Excel - What is the best library?](https://stackoverflow.com/questions/444522/import-and-export-excel-what-is-the-best-library) – VDWWD Mar 14 '18 at 22:33
  • I don't think any external library is needed. I believe data is not being bind properly. This is a link to pic https://i.stack.imgur.com/iYCEQ.png – ribash sharma Mar 14 '18 at 23:12

1 Answers1

2

It seems like you execute export function before you bind data to grid view. Try to load data in separate event and execute export function in Button4_Clickevent.

Check the sample code.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient; 
public partial class ExportGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView1.DataSource = BindData();
            GridView1.DataBind(); 
        }
    }

    private string ConnectionString
    {
        get { return @"Server=localhost;Database=Northwind;
        Trusted_Connection=true"; }
    }

    private DataSet BindData()
    {
        // make the query 
        string query = "SELECT * FROM Categories";
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Categories");
        return ds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;
        filename=FileName.xls");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite =
        new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for the
        specified ASP.NET server control at run time.
    }

//resource : https://www.daniweb.com/programming/web-development/threads/360606/how-to-export-data-from-gridview-to-excel-in-asp-net
}
PNP
  • 361
  • 5
  • 17