24

Reading csv file using JavaScript and HTML5

 2 years ago
source link: https://www.js-tutorials.com/javascript-tutorial/reading-csv-file-using-javascript-html5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Reading csv file using JavaScript and HTML5

CSV stands for comma-separated-values is the most popular file format to exchange information or data between cross programming languages.You can also use CSV to store information in spreadsheet or database. HTML5 provide FileReader API to read csv file using JavaScript. You can read CSV file from local or remote location.The Local files are opened with FileReader API, and remote files are downloaded with XMLHttpRequest.

This tutorial help to read CSV file using HTML5 and Papa parse library.Papa Parse is the fastest in-browser CSV parser for JavaScript. It is reliable and correct according to RFC 4180.You can also use jQuery to read csv data into HTML table.

Video Tutorial

If you are more comfortable in watching a video that explains about How to read CSV File Using javascript, then you should watch this video tutorial.

You can also check other recommended tutorial of CSV,

You can use core javascript code to read a CSV file using regular exp but using papaparse plugin, you get more advanced options to parse the CSV file. You can also use this library with jquery(not mandatory), that makes it easier to select files from the DOM. Papa parser support all modern browsers except IE10 below.

Features of Papa Parse?

  • Easy to use and fastest CSV parser
  • Parse CSV files directly (local or over the network)
  • Stream large files (even via HTTP)
  • Reverse parsing (converts JSON to CSV)
  • Auto-detect delimiter
  • Worker threads to keep your web page reactive
  • Header row support
  • Pause, resume, abort
  • Can convert numbers and Boolean to their types
  • Optional jQuery integration to get files from <input type="file"> elements

I will show you, how to read CSV file data from an uploaded CSV file. I will display that CSV data into HTML table. You can use this parsed data for further processing like sending to a server or storing in HTML5 local storage.

Read CSV file using Papa Parse

reading-csv-file-using-javascript

Step 1: Included papa parse and jQuery files into head section of index.html file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="papaparse.min.js"></script>

Step 2: Created HTML form markup to upload file, Let’s add below code into the index.html file.

<form class="form-inline">
<div class="form-group">
  <label for="files">Upload a CSV formatted file:</label>
  <input type="file" id="files"  class="form-control" accept=".csv" required />
</div>
<div class="form-group">
<button type="submit" id="submit-file" class="btn btn-primary">Upload File</button>
</div>
</form>

I used HTML5 file input with attributes like validation etc, As you can see file upload input field is a required field and allows to choose CSV formatted file.

Step 3: Initialize Papa parse to parse csv file and set config parameters. You need to add the below code at the bottom of the file.

$('#files').parse({
config: {
delimiter: "auto",
complete: displayHTMLTable,
before: function(file, inputElem)
//console.log("Parsing file...", file);
error: function(err, file)
//console.log("ERROR:", err, file);
complete: function()
//console.log("Done with all files");

The above JavaScript code will be executed when the submit file button is clicked. I am configuring some parameters using config objects, such as delimiter, callback complete function, and handlers. We are uploading CSV file and send data to papa parse instance, finally calling a submit callback function to perform parse operation to display CSV data into HTML table.

Step 4: Now we will define displayHTMLTable() function to display CSV data into table.

function displayHTMLTable(results){
var table = "<table class='table'>";
var data = results.data;
for(i=0;i<data.length;i++){
table+= "<tr>";
var row = data[i];
var cells = row.join(",").split(",");
for(j=0;j<cells.length;j++){
table+= "<td>";
table+= cells[j];
table+= "</th>";
table+= "</tr>";
table+= "</table>";
$("#parsed_csv_list").html(table);

in the above code, I am iterating csv file data and dynamically generating html table row using csv data.The Line 18 help to set HTML string data to div container where We will show csv data into listing.

How To Parse Single Integer Values with Comma Separated

One of the our user(Karen M. Green) send me a small bug fix to parse single string data with comma separated: 1,4,abcd,"5,7-9",10.

The input file has cell values with numeric ranges which include the comma.

The Above example will incorrectly split “5,7-9” to 5,”7-9” (two cells) instead of keeping it as one cell value.

This can be easily fixed by the following small change in Step 3, Need to change configuration object for the file parse add: header:false.

$('#files').parse({
config: {
delimiter: "",
  header: false,
  complete: displayHTMLTable

According to the Papa Parse documentation, it is only when the header is false that results. The data will have the desired data structure: an array of arrays – otherwise you get the other undesired structure.

If you add that (header:false), then you can avoid the error caused by the now unneeded line in Step 4:
var cells = row.join(",").split(",");

The above line should be removed.

You can download source code and Demo from below link.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK