CSV not importing - javascript

I am trying to create a csv editor. I want to import a csv and convert it to tables in html. This is the following code:
<html>
<head>
<title></title>
</head>
<body>
<div class="container">
<h1>Build Table</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file">
<div>
<table id="blacklistgrid">
<tr class="Row">
<td>
<input type="text"/>
</td>
<td>
<input type="text"/>
</td>
<td>
<input type="text"/>
</td>
</tr>
</table>
<button type="button" id="btnAdd">Add Row!</button>
<button>Export Table data into Excel</button>
</div>
<script>
function parseResult(result) {
var resultArray = [];
result.split("\n").forEach(function(row) {
var rowArray = [];
row.split(",").forEach(function(cell) {
rowArray.push(cell);
});
resultArray.push(rowArray);
});
return resultArray;
}
function createTable(array) {
var content = "";
array.forEach(function(row) {
content += "<tr>";
row.forEach(function(cell) {
content += "<td><input type=\"text\" value=\"" + cell + "\"/></td>" ;
});
content += "</tr>";
});
document.getElementById("#blacklistgrid").innerHTML = content;
}
jQuery(document).ready(function () {
jQuery('#btnAdd').click(function () {
jQuery( ".Row" ).clone().appendTo( "#blacklistgrid" );
});
var file = document.getElementById('file');
file.addEventListener('change', function() {
var reader = new FileReader();
var f = file.files[0];
reader.onload = function(e) {
var CSVARRAY = parseResult(e.target.result); //this is where the csv array will be
createTable(CSVARRAY);
};
reader.readAsText(f);
});
});
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function(i, row) {
var $row = $(row),
$cols = $row.find('input');
return $cols.map(function(j, col) {
var $col = $(col),
text = $col.val();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"';
// Deliberate 'false', see comment below
if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
// Crashes in IE 10, IE 11 and Microsoft Edge
// See MS Edge Issue #10396033
// Hence, the deliberate 'false'
// This is here just for completeness
// Remove the 'false' at your own risk
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) {
// HTML5 Blob
var blob = new Blob([csv], {
type: 'text/csv;charset=utf-8'
});
var csvUrl = URL.createObjectURL(blob);
$(this)
.attr({
'download': filename,
'href': csvUrl
});
} else {
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
}
// This must be a hyperlink
$(".export").on('click', function(event) {
// CSV
var args = [$('#blacklistgrid'), 'export.csv'];
exportTableToCSV.apply(this, args);
// If CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
</script>
</body>
</html>
I cannot get the import function to work. And, these are the following errors:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at createTable ((index):54)
at FileReader.reader.onload ((index):69)
What am I doing wrong?

Don't put # in the argument to document.getElementById. It should be:
document.getElementById("blacklistgrid").innerHTML = content;
or using jQuery:
$("#blacklistgrid").html(content);

Related

How to get XML file content in React? [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

How to input a file, and then filter it and output the result into a textarea?

I have the following code that you can upload a Javascript file and it removes all comments from the document. This works perfectly. However below that I have two textareas. One is where the user pastes their code, and the same function to remove all comments is run on that code and the updated code is pasted in the other textarea. However the result comes out as undefined. What is wrong with my code. Please help me!
function fileUploaded() {
var myUploadedFile = document.getElementById("myFile").files[0];
var reader = new FileReader();
reader.readAsText(myUploadedFile, "UTF-8");
reader.onload = function(evt) {
var documentNew = evt.target.result.replace(/(\r\n|\n|\r)/gm, "\n");
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = String(filterred).replace(/;/g, "; \n");
$("#answerDocument1").html(filterred);
};
};
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
$("#doc").keyup(function(evt) {
var doc = $("doc").html();
var documentNew = String(doc).replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = String(filterred).replace(/;/g, "; \n");
$("#answerDocument2").html(documentNew);
});
textarea {
width: 100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Upload A Javascript Document</h3>
<input type="file" id="myFile">
<textarea id="answerDocument1"></textarea>
<br><br>
<hr>
<br><br>
<textarea id="doc"></textarea>
<textarea id="answerDocument2" readonly></textarea>
I have used...
filterred = filterred.join("").replace(/;/g, "; \n");
Instead of...
filterred = String(filterred).replace(/;/g, "; \n");
Because filterred is an array, and not a string, and if you convert it into a string it comes out joined by commas.
I have also used $("#doc").val(); instead of $("doc").html();, because it is the value of the <textarea></textarea> that I am getting. That makes the undefined message go away.
function fileUploaded() {
var myUploadedFile = document.getElementById("myFile").files[0];
var reader = new FileReader();
reader.readAsText(myUploadedFile, "UTF-8");
reader.onload = function(evt) {
var documentNew = evt.target.result.replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = filterred.join("").replace(/;/g, "; \n");
$("#answerDocument1").html(filterred);
};
};
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
$("#doc").keyup(function(evt) {
var doc = $("#doc").val();
var documentNew = String(doc).replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = filterred.join("").replace(/;/g, "; \n");
$("#answerDocument2").html(filterred);
});
textarea {
width: 150px;
height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Upload A Javascript Document</h3>
<input type="file" id="myFile">
<textarea id="answerDocument1"></textarea>
<br><br>
<hr>
<br><br>
<h3>Paste Code</h3>
<textarea id="doc"></textarea>
<h3>Copy Formatted Code</h3>
<textarea id="answerDocument2" readonly></textarea>

JavaScript, csv to json, split is not a function [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Read a CSV file with javascript

I am trying to upload a CSV file to my database with php. I have problems with the numbers so I try to import the file in an array with javascript. I notice that the numbers of the CSV are different when I import it. For example the number 23447 is "23 447"(including the space and quotes). How can my code edit the form of the number?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
if (cells.length > 1) {
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
Just delete the spaces (whitespace characters are matched with the regex special character \s) then cast to a number. Apply this function to each csv cell value to process them:
const processNumber = str => {
const strWithoutSpaces = str.replace(/\s*/g, '');
const numberFromStr = +strWithoutSpaces;
return numberFromStr;
}
console.log(['10 000', '3 000 000', '100'].map(processNumber))

Reading uploaded text file contents in html

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Categories

Resources