I have checked by your Link button event also made same HTML Design as you describe but it work fine when we export grid to excel. Check the below sample code for your reference.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" AllowPaging="true"
PageSize="2" OnPageIndexChanging="gv_PageIndexChanging">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="Phone" HeaderText="Phone" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnExportar" />
</Triggers>
</asp:UpdatePanel>
</div>
<br />
<br />
<asp:LinkButton ID="btnExportar" runat="server" Text="Exportar" OnClick="btnExportar_Click" />
</form>
</body>
</html>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gv.DataSource = buscaInfo();
gv.DataBind();
}
}
protected void btnExportar_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Consulta.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = buscaInfo();
gv.DataBind();
foreach (GridViewRow row in gv.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "text";
}
}
gv.RenderControl(hw);
string style = @"<style> .text { mso-number-format:\@; } </style> ";
Response.Output.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
string msg = ex.ToString();
}
}
private DataTable buscaInfo()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("ContactName",typeof(string))
,new DataColumn("City",typeof(string))
,new DataColumn("Country",typeof(string))
,new DataColumn("Phone",typeof(string))
});
dt.Rows.Add("Vikas", "Mumbai", "India", "9999999999");
dt.Rows.Add("Vinayak", "Pune", "India", "8888888888");
dt.Rows.Add("Mohit", "Nashik", "India", "2222222222");
dt.Rows.Add("Ashok", "Dhule", "India", "1111111111");
dt.Rows.Add("Prashant", "Kolhapur", "India", "3333333333");
return dt;
}
protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
gv.DataBind();
gv.DataSource = buscaInfo();
gv.DataBind();
}
Screenshot
