使用Javascript将CSV转换为HTML表格.使用CSV中的列添加CSS类



我正在尝试制作一个JS,它从CSV中提取数据并创建一个HTML表。这是我目前的剧本。它工作正常,但我想添加功能。

我不想显示最后一列,而是使用这些数据来设置行的CSS类。

这只是我在修修补补和学习,所以一个解释而不仅仅是一个解决方案将是惊人的!

function pullData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.responseText;
var lines = data.split(/r?n|r/),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push(
"<tr><td>" + lines[i].split(",").join("</td><td>") + "</tr></td>"
);
output =
"<table><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th><th>Colour</th></tr>" +
output.join("") +
"</table>";
var div = document.getElementById("container");
div.innerHTML = output;
}
};
xhttp.open("GET", "data.csv", true);
xhttp.send();
}

它产生

JS 制作的表格

一个选项是将每一行的数据拆分为一个数组。然后使用pop()检索并删除数组中的最后一个元素,即颜色。然后将其用于类名或内联样式。

const data = `1,2,3,4,5,6,7,red
1,2,3,4,5,6,7,blue
1,2,3,4,5,6,7,green
1,2,3,4,5,6,7,yellow
1,2,3,4,5,6,7,orange
1,2,3,4,5,6,7,pink`;
var lines = data.split(/r?n|r/),
output = [],
i;
for (i = 0; i < lines.length; i++) {
let columns = lines[i].split(",");
output.push("<tr style='background-color:" + columns.pop() + "'><td>" + columns.join("</td><td>") + "</tr></td>");
}
output = "<table><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th></tr>" +
output.join("") +
"</table>";
var div = document.getElementById("container");
div.innerHTML = output;
<div id="container"></div>

最新更新