Reputation: 48402
I'm creating an MVC 5 / Bootstrap application. I have a need to allow the user to send table data to Excel. I know that TableTools can do that. However, I don't want to use DataTables/TableTools for anything else but export to Excel. I don't want to use it to do any table styling. I'm using Bootstrap for that.
So, is there a way I can use DataTables/TableTools for strictly this purpose? And I'd also like to be able to put a button somewhere on my form (not necessarily the default TableTools button), and, when clicked, do the Excel export. Is this possible?
Upvotes: 1
Views: 12504
Reputation: 131
I would say most likely not because the TableTools plugin is designed to operate on DataTables objects. Personally I wouldn't spend any time investigating this if don't wish to use DataTables, but rather I'll share an overview of how I implemented similar functionality for an ASP.NET MVC 5/Bootstrap site.
Simply placed a button on my view:
<button id="export" type="button">Export</button>
In the script section for my view I added a function for the click event (in this example, I am passing in my DataTable's additional parameters):
$("#export").click(function (e) {
var myTableSettings = dataTable.dataTableSettings[0];
$.ajax(
{
url: "GenerateCsv",
type: "POST",
data: myTableSettings.oAjaxData,
success: function (data) {
document.location.href = 'DownloadCsv';
}
error: function () {}
});
});
As the ajax call does not handle the headers to initiate a file download, it requires a two step approach: Firstly an ActionResult to generate the file ('GenerateCsv') and a FileStreamResult to return the file ('DownloadCsv').
In this case, I used LinqToCsv (http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library) to generate the CSV file. I mention the CSV format as TableTools creates a CSV file recognized by Excel and not a true Excel file (http://datatables.net/extensions/tabletools/buttons).
When I initially investigated TableTools I ran into an issue on how to re-bind my custom parameters when wishing to do a full table export using the Download plugin so found this approach preferable.
Upvotes: 3