A few days ago, I was doing some data crunching on a web application for a client. I needed a fast, simple way to work with Comma-separated Values (CSV) files i.e. update, download and upload using the existing JavaScript libraries.
The libraries involved are DataTables and PapaParse. Both are open source libraries.
PapaParse
The powerful, in-browser CSV parser for big boys and girls.
DataTables
If you work as website developer / designer, chances are you’ve used DataTable. It’s one of the oldest, robust and well maintained jQuery JavaScript library for HTML table. Highly customisable, one of many reasons I prefer DataTable over similar libraries.
Possible Scenario — Tasks
Let’s say you need a component in your bootstrap web application where you can upload a CSV file and perform the below operation;
- Filter out rows
- Remove some columns
Workaround
First, we create an event listener to listen to file input change. Once a file is selected, it will be parsed to Array using PapaParse. Now that we have the conversion, it is passed to htmlTableGenerator function for processing.
Generate HTML Table
Get head and body values from the array and use it to generate the table. The first array is the header.
Initialise DataTable
DataTable configuration can be comprehensive depending on your needs. The library comes with loads of extensions and plugins. Two used for this example are Column visibility (colvis) and CSV export. There are several more, you can check them out here.
Demonstration
Now we have all we need to make above scenario tasks work. To select a CSV file and other steps, look below
Select and Load CSV File
We select a CSV file and load it into the above functions.
Filter and Remove
Next step is we choose the columns we want and filter out some row. For this sample we want to show below;
- Columns: Title, Content Type, Short URL and Archive
- Rows: Magazines
Download as CSV
Let’s download the above result as new CSV. You can also upload the new file into a server (that was not covered).
The sample demonstrated above was simplified so anyone with basic understanding of web application development can utilise it. The application of DataTables can be very extensive. It is also important to note that the sample CSV data used was 1100 rows. When using file with tens of thousands rows, this technique won’t be efficient.
You can find the complete source code in my GitHub account and if you’re interested in snippets… checkout GitHub gist;