How to read csv data in html table using Javascript ( JS )


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

  • The first line `<!DOCTYPE html>` declares that this is an HTML file.
  • The `<html>` tag marks the beginning of the HTML code.
  • The `<head>` section contains information about the HTML document, such as the title of the page and any external files that are linked to the document. In this case, there is a `<title>` tag that sets the title of the page to "csv file reader", and a `<style>` tag that adds some CSS to the HTML page.
  • The `<meta>` tags specify metadata about the HTML document, such as the character encoding and viewport settings.
  • The `<title>` tag sets the title of the HTML page, which appears in the browser tab.
  • The `<style>` tag sets a CSS style for all `<td>` elements in the HTML page. In this case, the style adds a 2-pixel wide maroon border to each `<td>` element.
  • The `<body>` section contains the visible content of the HTML page. In this case, there are three elements: an `<a>` tag that links to a tutorial on YouTube, an `<input>` element that allows the user to select a CSV file, and an empty `<table>` element.
  • The `<a>` tag adds a link to a YouTube tutorial. When the user clicks on the link, they will be taken to the YouTube video.
  • The `<input>` tag adds an input element that allows the user to select a file from their computer. This input element is of type "file", which means that it will only allow the user to select files. When the user selects a file, the file's contents can be read and processed using JavaScript.
  • The `<table>` tag adds an empty table element to the HTML page. This table will be populated with data from the CSV file that the user selects.
  • The `<script>` tag includes a JavaScript file called "csv.js". This file contains functions that handle the CSV file that the user selects.

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.


css free-source-code html javascript
Newer Post Home

Popular Posts