Clue Mediator

Read CSV file from URL in HTML using JavaScript

📅May 4, 2023

In web development, it is common to need to read data from a CSV file and display it on a web page. CSV (Comma Separated Values) files are a popular way to store and share data between different applications. In this tutorial, we will learn how to read a CSV file from a URL using JavaScript in an HTML document.

Prerequisites

To follow this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript.

Step 1: Create an HTML page

Create an HTML page with a table element where the data from the CSV file will be displayed.

<!DOCTYPE html>
<html>

<head>
  <title>Read CSV file from URL in HTML using JavaScript - Clue Mediator</title>
</head>

<body>
  <h1>CSV Data - Clue Mediator</h1>
  <table id="csv-data"></table>
  <script src="script.js"></script>
</body>

</html>

Step 2: Add JavaScript code to read the CSV file

In the script.js file, add the following code to read the CSV file from the URL and display it in the table element.

let table = document.getElementById("csv-data");
let url = "https://example.com/data.csv";

fetch(url)
  .then(response => response.text())
  .then(data => {
    let rows = data.split("\n");
    for (let i = 0; i < rows.length; i++) {
      let cells = rows[i].split(",");
      let row = table.insertRow();
      for (let j = 0; j < cells.length; j++) {
        let cell = row.insertCell();
        cell.innerText = cells[j];
      }
    }
  })
  .catch(error => console.log(error));

In this code, we first get the table element by its ID and the URL of the CSV file. We use the fetch() function to make a request to the URL and get the data from the CSV file as a text string. We then split the text into rows and cells using the split() function and loop through them to create the rows and cells of the table. Finally, we catch any errors that may occur and log them to the console.

Step 3: Test the code

Open the HTML page in a web browser and you should see the data from the CSV file displayed in the table element.

Conclusion

In this tutorial, we have learned how to read a CSV file from a URL using JavaScript in an HTML document. We used the fetch() function to make a request to the URL and get the data from the CSV file as a text string. We then split the text into rows and cells and looped through them to create the rows and cells of the table. This can be a useful technique for displaying data from CSV files on web pages.