I have to page in my web page that allows you to search for a list of names and it returns the results into a grid view. When the search result appears, the export button appears. I have the export button there for the user to click and it export the data from the grid view into excel in xlsx format. This is my current code:
ASP
<asp:TableCell>
<asp:DataGrid ID="ResultGrid" runat="server"
AutoGenerateColumns="false"
EnableViewState="false"
</asp:TableCell>
<asp:TableCell>
<asp:Button class="myClass" ID="export" runat="server" OnClick="ExportBtn_Click" Text="Export" />
</asp:TableCell>
C#
protected void ExportBtn_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=myexcelfile.xls");
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ResultGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Currently this downloads a blank excel file... even though my grid view has one item in it upon search.
My additional question (even though I know it is frowned upon), is how to export as xlsx instead of xls. If I replace the xls with xlsx, it tells me it is in the wrong format when I click my export button (when it tries to open up in excel).
To wrap up, my two question are: why is it returning nothing in excel even though I have a row returned in grid view and how to export as xlsx instead of xls?