Skip to content
Advertisement

DataTable to csv file

I have created a web page using bootstrap/thymeleaf where I show some data tables using Ajax. And I have the buttons to export to CSV, but what I need is to generate a temporary file from this datatable and get the path to my controller when the datatable is already loaded with the data using a button.

So I need a way to do that creating a new function, but I don’t really know how to do it. May be without call again my sql repository because tables are very large.

JavaScript Code

JavaScript

Controller

JavaScript

HTML/Bootstrap

JavaScript

Advertisement

Answer

I think the easiest way would be to create the csv files using JS on the client-side.

First of all, you will need to get the data from your DataTable, their documentation shows it could be done like this:

JavaScript

Now, csv format is basically a text format with separators. So you need to iterate over the rows in data and merge cells to separate text rows, something like this:

JavaScript

Then you only need to create a document and download it. To do that I would suggest the usage of filesaver.js:

JavaScript

Please note that I have never worked with DataTables, so I might be mistaken about the data structure in which it returns the data from table after .rows().data() (I assumed it returns an array of arrays that represent the cells in the rows). The general approach should be correct.

Edit

However I would not recommend sending data from the browser to the server – just create the correct file on the server side insted. E.g. like this:

JavaScript
Advertisement