Read and Display CSV Files Using JavaScript



Source code to read csv files in html table using javascript.

Save this html and name it to "csv-file-reader.html" or anything what you want.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>csv file reader</title>

    <!-- Add a CSS style to the HTML page -->
    <style>
        td {
            border: 2px solid maroon;
        }
    </style>
</head>
<body>
    <!-- Add a link to a tutorial on YouTube -->
    <!-- This link could be helpful for someone who is learning how to use this code. -->
    <a href="https://www.youtube.com/watch?v=BQfK1QKCHys&t=326s">tutorial link</a>

    <!-- Add an input element that allows the user to select a CSV file -->
    <input type="file">

    <!-- Add an empty table element to the HTML page -->
    <table></table>

    <!-- Include a JavaScript file called "csv.js" -->
    <!-- This file might contain functions that handle the CSV file that the user selects. -->
    <script src="./csv.js"></script>
</body>
</html>


Explanation of above HTML

Copy and Save the below script file giving a name "csv.js"


     // Select the input element and store it in a variable named "x"
const x = document.querySelector("input");

// Add an event listener to the input element that listens for a "change" event
x.addEventListener("change", () => {
  // Create a new FileReader object
  const fr = new FileReader();

  // When the FileReader object has finished loading the file, run the following code
  fr.onloadend = e => {
    // Split the contents of the file into an array of lines, then split each line into an array of values
    let r = fr.result.split("\n").map(e => {
      return e.split(",");
    });

    // For each row in the CSV file, create a new tr element and add it to the table element
    r.forEach(e => {
      // Map each value in the row to a string, then join the strings together with no separator
      let m = e.map(e => {
        return `${e}`;
      }).join("");
      // Create a new tr element and set its innerHTML to the string of values
      const ce = document.createElement("tr");
      ce.innerHTML = m;

      // Only add the tr element to the table element if it contains any text
      if (ce.innerText !== "") {
        document.querySelector("table").append(ce);
      }
    });

    // Uncomment the following line to log the parsed CSV data to the console
    // console.log(r)
  }

  // Read the contents of the selected file as text
  fr.readAsText(x.files[0]);
});

Explanation of above code

  1. The code selects the first `input` element on the page and stores it in a variable named `x` using the `document.querySelector` method.
  2. An event listener is added to `x` that listens for the `change` event, which is triggered when a new file is selected using the file input dialog.
  3. When the `change` event is triggered, a new `FileReader` object is created using the `FileReader` constructor. This object is used to read the contents of the selected file.
  4. The `FileReader` object's `onloadend` property is set to a function that will be called when the file has been completely loaded.
  5. Inside the `onloadend` function, the `result` property of the `FileReader` object is split by newline characters (`\n`) to create an array of lines.
  6. Each line in the array of lines is then split by commas (`,`) to create an array of values for each row of the CSV file.
  7. The resulting array of arrays is stored in a variable named `r`.
  8. A `forEach` loop is used to iterate over each row in `r`.
  9. For each row, a new `tr` element is created using the `document.createElement` method.
  10. The values in the row are mapped to an array of strings using the `map` method, and then joined together with an empty string (`""`) using the `join` method.
  11. The resulting string is set as the `innerHTML` property of the `tr` element.
  12. If the `innerText` property of the `tr` element is not an empty string, the `tr` element is appended to the `table` element on the page.
  13. If the `console.log` statement is uncommented, the parsed CSV data will be logged to the console.

More Posts For You!


5 More HTML Tricks For You

5 HTML Tricks That You Can Use To Enhance Your Web Pages

Effortlessly Convert Excel to JSON with JavaScript: Streamline Your Data Management with Sheet Js

Integrating OCR Capabilities into Web Applications with JavaScript and AppScript

Efficient Text Extraction from PDFs: Implementing OCR with JavaScript and AppScript

Build a CRUD Application Using Google Sheets as Database with HTML, CSS, and JavaScript

Integrating OpenAI with Google Sheets using AppScript for Automated Responses

Upload Images to Google Drive and Google Sheets from HTML File Input: A Complete JavaScript and AppScript Guide

Convert HTML and CSS to PDF with JavaScript Using HTML2PDF.js

Create a Functional Contact Form Using HTML, CSS, JavaScript, and Google AppScript

Build a CRUD App Using HTML, CSS, JavaScript, and IndexedDB API

Reading Data From Google Sheets to HTML Using JavaScript and Apps Script

PrevNext