In today's video, I will be showing you how to display multiple CSV files in an HTML table using JavaScript. First, we will convert CSV files to a javascript array then we will display them in an HTML table.
Create a index.html file and paste the below code
<!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>Read CSV files with javascript fetch method</title>
<style>
td,
th {
border: 2px solid blue;
}
table {
display: none;
}
nav {
width: 100%;
display: flex;
align-items: center;
justify-content: space-evenly;
}
:target {
display: block;
}
</style>
</head>
<body>
<nav id="nav">
</nav>
<h1>CSV Data Reader</h1>
<script src="./csv.js"></script>
</body>
</html>
Create a csv.js file and paste the below code
let fa = [
// replace the path value with your csv files path
{ path: "/static/1.csv", head: "CSV1" },
{ path: "/static/2.csv", head: "CSV2" },
{ path: "/static/3.csv", head: "CSV3" },
]
for (let i = 0; i < fa.length; i++) {
document.querySelector("#nav").innerHTML += `
${fa[i].head}
`;
document.querySelector("body").innerHTML += `
${fa[i].head}
`;
fetch(fa[i].path)
.then(res => res.text())
.then(data => {
let result = data.split(/\r?\n|\r/)
.map(e => {
return e.split(",")
.map(td => td !== "" ? `${td} ` : "")
.join("")
.split("\n")
.map(tr => tr !== "" ? `${tr} ` : "")
.join("");
})
document.querySelector(`#tbody${i}`).innerHTML = result.join("");
// console.log(result);
})
}