xxxxxxxxxx
86
// Print all rows and columns
// Given the following CSV file called "mammals.csv"
// located in the project's "assets" folder:
//
// id,species,name
// 0,Capra hircus,Goat
// 1,Panthera pardus,Leopard
// 2,Equus zebra,Zebra
let table;
function preload() {
//my table is comma separated value "csv"
//and has a header specifying the columns labels
table = loadTable('mammals.csv', 'csv', 'header');
//the file can be remote
//table = loadTable("http://p5js.org/reference/assets/mammals.csv",
// "csv", "header");
}
function setup() {
// createCanvas(windowWidth, windowHeight);
//count the columns
print(table.getRowCount() + ' total rows in table');
print(table.getColumnCount() + ' total columns in table');
print(table.getColumn('name'));
//["Goat", "Leopard", "Zebra"]
//cycle through the table
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++) {
print(table.getString(r, c));
}
noCanvas();
noLoop();
// https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < table.getRowCount(); i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < table.getColumnCount(); j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode(table.getString(i, j));
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
// function draw() {
// background(0);
// textSize(32);
// fill(255);
// for (let r = 0; r < table.getRowCount(); r++){
// for (let c = 0; c < table.getColumnCount(); c++) {
// text(table.getString(r, c),
// 10 + c * 200, 300 + r * 300);
// }
// }
// }