In this article I will explain with an example, how to export (convert) GridView to Excel file using JavaScript and jQuery in ASP.Net.
HTML Markup
The following HTML Markup consists of an ASP.Net GridView and an HTML Button.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="80" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
<br />
<input type="button" id="btnExport" value="Export" />
Exporting (Converting) GridView to Excel using JavaScript and jQuery in ASP.Net
The Export Button has been assigned a jQuery click event handler.
When the Export Button is clicked, the jQuery table2excel plugin is applied to the GridView’s HTML Table and the GridView is converted (exported) to Excel file. The jQuery table2excel plugin accepts filename parameter which sets the name of the Excel file.
Note: You will get a Warning message from Microsoft Excel application when you try to open the generated Excel file. This Warning is shown because the generated file is not a valid Excel format as the plugin simply exports the HTML content to an Excel file.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="table2excel.js" type="text/javascript"></script>
<script type="text/javascript">
$("body").on("click", "#btnExport", function () {
$("[id*=GridView1]").table2excel({
filename: "Table.xls"
});
});
</script>
Screenshots
The GridView
Excel file being downloaded when Export Button is clicked
The generated Excel file
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads