Read CSV file from URL in HTML using JavaScript
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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.