Reorder csv rows and columns - javascript

I have This csv file I want the output to be in a html table where the
Example :
fish;4;1;33 fish should be at 1 row column 4.
dog;5;2;66 dog should be at 2nd row column 5
I have come here:
var data ='Major;1;2;29/nMinor;2;3;29/nRowNum;1;1;23/njk;2;2;23/n44;1;‌4;23';
function insertData(id, data)
{
var table = document.getElementById(id);
var dataRows = data.split("/n");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
}); }
This code inserts major and minor where it should but how can do the same by uploading a document?Basically var data = //uploaded doc
I have tried to do it with
myReader.onload = function(e) {
var content = myReader.result;
but no good result,I would really appreciate some help!

<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
var data = e.target.result;
// You can process your file here
var datasplitted = data.split("/n");
// you do all you want
});
reader.readAsBinaryString(myFile);
}
});
}
</script>
</body>

Related

Any way to automatically reload a file selected from "InputFile" through Filereader?

I am trying to display a CSV file into an HTML table.
I have it set up so that you can pick the CSV and it will successfully show in HTML format.
Is there anyway to refresh this so that if the selected file Changes, the HTML format will change with it (Without user input re-selected the file.
Code and Table are below. But basically I would like it so that if the population of New York changed in the table, that the HTML table is automatically updated as well.
<!DOCTYPE html>
<html lang="en">
<input type="file" id="fileUpload" onchange="Upload()"/>
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<hr />
<div id="dvCSV">
</div>
<script type="text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
}
}
</script>
<script type="text/javascript">
Upload();
setInterval(function(){ Upload(); }, 10000);
</script>
</html>
rank
place
population
1
New York
8175133
2
Los Angeles
3792621
3
Chicago
2695598

Importing data to localstorage

Could anybody help me out sorting the following code or help me in the right direction?
It needs to import data from a .txt file and store it into localstorage as key & value.
Key is before ':' and value comes after it. A new key / value is separated after each ','.
Sample data from .txt file is:
nl-step1chapter1Question6:U2FsdGVkX19bRT84xShxK+29ypgj1d6ZHt+2DVBCUtY=,nl-step1chapter1Question1:U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=,nl-step1chapter1Question4:U2FsdGVkX1+9SVVOvTKeZuaQGj58L5WnEgL8htS0c7U=,jft:320982da-f32a-46a2-a97c-605ebe305518,nl-step1chapter1Question5:U2FsdGVkX19pi8A+PQZ7rBNCWrFeCwl2HdXpV+wWkFk=,nl-step1chapter1Question2:U2FsdGVkX19hnRnpmP3omzYNU0jXd3NtsHM+mvGYBnc=,nl-step1chapter1Question3:U2FsdGVkX1+hPbMRN+x19y7pF73eXoxG0qK1igZYZbA=
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="application/x-javascript">
$(function importData() {
document.getElementById('file').onchange = function () {
//debugger;
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (progressEvent) {
//console.log(this.result.split(','));
var lines = this.result.split(',');
var list = [];
for (var line = 0; line < lines.length; line++) {
list.push(lines[line]);
localStorage.setItem([line],lines);
}
};
reader.readAsText(file);
};
});
</script>
Any help is much appreciated!
The way you are using FileReader doesn't seem correct to me. This is how your importData() function should be:
$(function importData() {
document.getElementById('file').onchange = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var text = reader.result;
var lines = text.split(',');
for (var line = 0; line < lines.length; line++) {
let elements = lines[line].split(':');
localStorage.setItem(elements[0], elements[1]);
}
};
reader.readAsText(input.files[0]);
};
});
It will insert the elements in the localStorage as you described. For example: key = step1chapter1Question1 and value = U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=

Reading excel file into array using javascript

I'm trying to read an excel file and create a multidimensional array in javascript with it.
The excel file will look like:
AA11 AA22 AN65
AB11 AB22 AN64
...
I need it to create an array that looks like:
[
[AA11, AA22, AN65],
[AB11, AB22, AN64]
]
So far, I've been able to bring up a file selection window, and I believe it's reading the file, I just think it might not be putting the data into the array correctly. This is what I have so far:
<script type="text/javascript">
$(function () {
$("#input").on("change", function () {
var excelFile,
var array = [[],[]];
fileReader = new FileReader();
$("#result").hide();
fileReader.onload = function (e) {
var buffer = new Uint8Array(fileReader.result);
$.ig.excel.Workbook.load(buffer, function (workbook) {
var column, row, newRow, cellValue, columnIndex, i,
worksheet = workbook.worksheets(0),
columnsNumber = 0,
gridColumns = [],
data = [],
worksheetRowsCount;
while (worksheet.rows(0).getCellValue(columnsNumber)) {
columnsNumber++;
}
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
column = worksheet.rows(0).getCellText(columnIndex);
gridColumns.push({ headerText: column, key: column });
}
for (i = 1, worksheetRowsCount = worksheet.rows().count() ; i < worksheetRowsCount; i++) {
newRow = {};
row = worksheet.rows(i);
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
cellValue = row.getCellText(columnIndex);
//newRow[gridColumns[columnIndex].key] = cellValue;
array[row,columnIndex] = cellValue;
}
window.alert(array[0][0]);
data.push(array);
}
</script>
Any help would be greatly appreciated.
Not sure what you're using to parse the Excel, is it IgniteUI ? For what it's worth, the free (community edition) of SheetJS, js-xlsx provides a few functions that produce exactly the output you needed, given the spreadsheet you provided.
The docs are a bit messy, but they are complete, the most interesting sections for this use-case are: Browser file upload form element under Parsing workbooks and XLSX.utils.sheet_to_json. You can run a test with the type of spreadsheet you provided in the code sample below:
$("#input").on("change", function (e) {
var file = e.target.files[0];
// input canceled, return
if (!file) return;
var FR = new FileReader();
FR.onload = function(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, {type: 'array'});
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
// header: 1 instructs xlsx to create an 'array of arrays'
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
// data preview
var output = document.getElementById('result');
output.innerHTML = JSON.stringify(result, null, 2);
};
FR.readAsArrayBuffer(file);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="input" accept=".xls,.xlsx,.ods">
<pre id="result"></pre>
Here the full solution aditionally I've added a group by category function
to demostrante that we can apply functions to the json array.
(async() => {
const url = "./yourfile.xlsx";
const data = await (await fetch(url)).arrayBuffer();
/* data is an ArrayBuffer */
const workbook = XLSX.read(data);
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const sheetValues = XLSX.utils.sheet_to_json(worksheet);
const groupByCategory = sheetValues.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});
console.log(groupByCategory)
/* DO SOMETHING WITH workbook HERE */
})();

How can we upload multiple html files and replace the text inside and get the output html pages with the help of javascript

From following code it accepts Single File and process it & display output.but can it be possible to accept multiple files and process & then return output.
<html>
<head>
</head>
<body>
<div>
<label for="text">Choose file</label>
<input id="text" type="file" name="photo">
</div>
<textarea id="finalHTML" style="height:200px;width:80%">
</textarea><br/>
<button id="save">Save</button>
<script>
$('input').change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'œ',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[0]);
//reader.readAsDataURL(this.files[0]);
}
});
var button2 = document.getElementById('save');
button2.addEventListener('click', saveTextAsFile);
function saveTextAsFile()
{
var textToWrite = $('#finalHTML').text();
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "sample1.html"/*Your file name*/;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
</script>
</body>
</html>
I am not able to accept multiple files and process on it,and return Output.
Any one can help me out please.
You used input type 'file' there is an attribute multiple ="multiple" which allows you to select multiple file at once. How to handle those files using JavaScript? you can look at this link ...Multiple-files-selected
try this and look at the for loop block... I'm not tasted it...
$('input').change(function(){
for(var i = 0; i<= files.length; i++){
if (this.files && this.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'œ',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[i]);
//reader.readAsDataURL(this.files[0]);
}
}
});

using js to parse log and filter out something

I am quite new in javascript and I am trying to parse the log and filter out something. The log looks like:
v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
The output should be printed by splitting on ,, line by line and also filter out something that I don't need. e.g, I only need ip and rr attributes, so the output should look like:
ip='99.114.107.39'
rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv
The code I have is following, but it doesn't work:
<!doctype html>
<html>
<head>
<title>reading file</title>
<script>
function readText(obj){
var file = obj.files[0],
div=document.getElementById('main');
if(file){
div.innerHTML='';
var reader = new FileReader();
reader.onerror = function(event){
div.innerHTML='The file can\'t be read! Error ' + event.target.error.code;
}
reader.onload = function(event){
var cont = event.target.result.split(',');
for(var i=0; i<cont.length; i++){
var name = cont.split('=');
if (name[0]==="rr") {
div.innerHTML+=cont[i]+'<br />';
}
}
}
reader.readAsText(file);
}
}
window.onload=function(){
document.getElementById('ff').onchange=function(){readText(this);}
}
</script>
</head>
<body>
<input type="file" id="ff" />
<div id="main"></div>
</body>
</html>
Use javascript's split():
DEMO
Example:
window.onload = function () {
var text = "v=5,ci=3,si=60,sv=1,ss=active,es=-,ai=a23-369b-4da3-b2da-630aee75f8c5,ip='99.114.107.39',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,rr='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%2Fv";
var ip = '',
rr = '';
var splits = text.split(',');
for (var i = 0; i < splits.length; i++) {
if (splits[i].indexOf('ip') > -1)
ip = splits[i];
else if (splits[i].indexOf('rr') > -1)
rr = splits[i];
}
document.getElementById('divIp').innerHTML = ip;
document.getElementById('divRr').innerHTML = rr;
};

Categories

Resources