Reputation: 53
I am making a simple table page and I don't want to manually add rows using HTML. I have about 100 rows of data and I am working in a Static Environment so JavaScript is the only option I have (or the only one I know maybe able to do this).
I did try some tutorials and did find a way to import CSV to HTML. I used this tutorial and it worked like charm.
But the issue is that the tutorial uses an <input>
tag to get the File Object. I only have a single CSV file locally stored in the same folder as the Web Page. I tried looking up for File objects and Blobs but I am not able to make it work so far. None of my functions work.
Upon opening, I want my page to directly load the data from the CSV and put it in A Table. I do know how to add table code to the html page using innerHTML but I just haven't been able to import the actual CSV data. Please help!
Upvotes: 0
Views: 4763
Reputation: 46
For security reasons it is not allowed to read OS files with JS from the browser. For this you must have the CSV file and the html page from where you want to read it on the same server and using ajax or some server side language generate a JSON. I give you an example in ajax
$(document).ready(function() {
$.ajax({
type: "GET",
url: "datatable.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var record_num = 5; // or however many columns there are in each row
var allTextLines = allText.split(/\r\n|\n/);
var entries = allTextLines[0].split(',');
var lines = [];
var headings = entries.splice(0,record_num);
while (entries.length>0) {
var tarr = [];
for (var j=0; j<record_num; j++) {
tarr.push(headings[j]+":"+entries.shift());
}
lines.push(tarr);
}
// alert
OR use this library https://www.cssscript.com/lightweight-csv-table-converter-csvtotable-js/
Upvotes: 2