Quick way to display CSV files as HTML tables

During database projects I frequently need to export certain views or intermediate results as CSV files. These are further used for importing into other databases. However, many times it is required to display the CSV files in web pages as HTML tables. As most times the data is generated on the fly it requires some JavaScript to turn the CSV data to HTML. One of my current favorite is the csv-to-html-table library. This allows you to easily integrate CSV files into your web pages.

Installation and Usage

Download from github or clone it.

git clone git@github.com:derekeder/csv-to-html-table.git

After installation copy the CSV file you want to display to the data/ folder and add the following JavaScript code to where you want to display the table. The table-container div will hold the displayed CSV table. In this example we will use the ‘countries’ CSV dataset from worlddata. A sample CSV data is shown below:

"Country (en)";"Country (de)";"Country (local)";...
"Afghanistan";"Afghanistan";"Afganistan/Afqanestan";...
"Egypt";"Ägypten";"Misr";"EG";"Africa";...
"Albania";"Albanien";"Shqipëria";"AL";...
"Algeria";"Algerien";"Al-Jaza’ir/Algérie";"DZ";...

Code to display the CSV data.

.
<div id='table-container'></div>
.
 
<script>
  CsvToHtmlTable.init({
    csv_path: 'data/countries.csv',
    element: 'table-container', 
    allow_download: true,
    csv_options: {separator: ';', delimiter: '"'},
    datatables_options: {"paging": false}
  });
</script>

That’s it. Now you have your CSV file displayed as a HTML table. The library relies on a few other dependencies – jQuery, jQuery CSV, Bootstrap and DataTable. Note that these are already included in the download.

You can add pagination, change display style and other options using the DataTables plugin options. Also you can change the CSV parsing options and set delimiters. The tables are easily sortable and can also be searched.

You can add custom formatting and processing to individual CSV columns before displaying. For example to convert all the entries in the first column to uppercase you can write as follows. This will pass the first CSV field to the to_uppercase method which will than convert the field to uppercase. You can also use this method to validate any fields before displaying. Note that the first field index starts with a ‘0’.

<script>
      function to_uppercase(country){
        if (country)
          return country.toUpperCase();
        else
          return "";
      }
 
      CsvToHtmlTable.init({
        csv_path: 'data/countries.csv', 
        element: 'table-container', 
        allow_download: true,
        csv_options: {separator: ';', delimiter: '"'},
        datatables_options: {"paging": false},
        custom_formatting: [[0, to_uppercase]]
      });
</script>

The user can also download the CSV from the page if you set the allow_download option to ‘true’.