How to display key based values from a text file? - javascript

I am working on a text file uplaoding process, where you can display the values based on a key such as First Name. Here is the sample text
First Name : Joe
Last Name : Smith
Age : 21
Now how can I display only the values which is based on the key?
function process() {
var input = fileInput.get(0);
console.log(input);
var reader = new FileReader();
var textFile = input.files[0];
reader.readAsText(textFile);
$(reader).on('load', processFile);
}
function processFile(e) {
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
var FirstName = results[0];
var LastName = results[1];
var Age = results[3];
alert(FirstName);
alert(LastName);
alert(Age);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file" id="files" />
<button id="upload" onclick="process()">Upload</button>
</form>

Here is a demo working in base of your code, the matter you got is the DOM selector of the input mine is this
var input = document.getElementsByTagName('INPUT')[0];
nd the all demo is :
function process() {
var input = document.getElementsByTagName('INPUT')[0];
console.log(input);
var reader = new FileReader();
var textFile = input.files[0];
reader.readAsText(textFile);
$(reader).on('load', processFile);
}
function processFile(e) {
console.log(e);
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
var FirstName = results[0];
var LastName = results[1];
var Age = results[3];
alert(FirstName);
alert(LastName);
alert(Age);
}
}

Related

How to access to specific row of excel file using Javascript

I am reading random row of large Excel file using Javascript. But it is taking some time for example when I am working with 300.000 row data in excel file. I need fast way.
<body>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<!-- <input type="button" id="upload" value="Random" onclick="ProcessExcel()" /> -->
<hr />
<h1 id="exc">Hello</h1>
<p id="her"></p>
<p id="limm"></p>
<div id="dvExcel"></div>
<script type="text/javascript">
// var gl_ex = "";
function Upload() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
ProcessExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
ProcessExcel(data);
// gl_ex = data;
//alert("Uploaded.");
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function ProcessExcel(data) {
//var data = "";
//data = gl_ex;
//Read the Excel File data.
var workbook = XLSX.read(data, {
type: 'binary'
});
//Fetch the name of First Sheet.
var firstSheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
var len = excelRows.length;
var rand_num = Math.floor((Math.random() * len) + 1);
document.getElementById("her").innerHTML = rand_num;
document.getElementById("limm").innerHTML = len;
document.getElementById("exc").innerHTML = excelRows[rand_num-1].Name;
};
</script>
</body>
As in example shown I am reading random row from Excel file. I think javascript is reading whole excel file sequentially. Can I read specific row data in faster way?

Javascript - FileReader how can I read and process each file at a time among multiple files

I am trying let the user drop multiple excel file and extract desired values from each one of the files and upload it to website ONE FILE AT A TIME.
My code is not working, and I am assuming this is because of the callback problem..
Could anybody help?
Edit: I also added my uploadFile function. I very much appreciate your help.
for(var i = 0; i < fileList.length; i++) {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if(!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try{
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if(ein == undefined || engCode == undefined || goLocator == undefined){
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if(hasValues && isValid){
uploadFile(fileList[i], userInfo);
} else {
noValueErrorHandler(errMsg);
}
} catch(err){
hasValues = false;
}
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
function uploadFile(f, userInfo) {
// Define the folder path for this example.
var serverRelativeUrlToFolder = listName;
// Get info of the file to be uploaded
var file = f;
var fileInput = file["file"];
var newName = file["fileName"];
var ein = file["EIN"];
var engCode = file["EngagementCode"];
var email = userInfo;
var goLocator = file["GoSystem"];
console.log("file: " + file);
// Get the server URL.
var serverUrl = _spPageContextInfo.siteAbsoluteUrl + "/StatusTracker";
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileInput);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer, newName);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
processedCount += 1;
if (processedCount < fileCount) {
uploadFile(fileList[processedCount], email);
} else if (processedCount == fileCount){
$("#dropbox").text("Done, drop your next file");
$("#ADMNGrid").data("kendoGrid").dataSource.read();
fileList = [];
alert("Total of " + processedCount + " items are processed!");
}
// Refresh kendo grid and change back the message and empty fileList
//$("#dropbox").text("Drag your Fund/Lower Tier workpaper here ...");
//location.reload(true);
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
You might put the whole thing into an async function and await a Promise for each iteration, forcing the files to be processed in serial. You didn't post your uploadFile, but if you have it return a Promise that resolves once it's done, you could do the following:
async fn() {
for (var i = 0; i < fileList.length; i++) {
await new Promise((resolve, reject) => {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if (!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {
type: rABS ? 'binary' : 'array'
});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try {
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if (ein == undefined || engCode == undefined || goLocator == undefined) {
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if (hasValues && isValid) {
uploadFile(fileList[i], userInfo)
.then(resolve);
} else {
noValueErrorHandler(errMsg);
reject();
}
} catch (err) {
hasValues = false;
reject();
}
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
});
}
}

use same function for multiple file upload events

I have used js-xlsx plugin to parse JSON from an excel file. I am parsing JSON from multiple excel files and I want to use the same parsing function to load the result in multiple dropdowns. I have two upload file inputs and two corresponding dropdowns. I am able to get the xlFileName and sheetNames only for the first dropdown. If I want to upload a different excel file using the second file upload input and want to load the xlFileName and sheetNames for the corresponding excel file in the second dropdown how can I use the same JS functions to achieve this. Thanks in advance. (I have tried switch case to get the ids of upload file inputs but didn't know how to get it done right)
HTML:
<input type="file" style="display:none;" name="files" id="inputFile1" />
<span data-bind="text: fileNameXl1"></span>
<select id="dropdown3" required="required" class="form-control select2" data-bind="options:xlnames,value:selectedSheetname1,
selectedOptions: chosenFile,optionsCaption:'Please Select Sheet Name'">
</select>
<input type="file" style="display:none;" name="files" id="inputFile2" />
<span data-bind="text: fileNameXl1"></span>
<h4 class="header-title m-t-0 m-b-30">Select Sheet name(Macro):</h4>
<select id="dropdown4" required="required" class="form-control select2" data-bind="options:xlnames1,value:selectedSheetname2,
selectedOptions: chosenFile,optionsCaption:'Please Select Sheet Name'">
</select>
JS:
self.selectedSheetname1 = ko.observable("");
self.selectedSheetname2 = ko.observable();
self.selectedSheetname3 = ko.observable();
self.chosenFile = ko.observable();
self.xlnames = ko.observableArray([]);
self.xlnames1 = ko.observableArray([]);
self.fileNameXl1 = ko.observable();
self.handleFile = function(e) {
var files = e.target.files;
var f = files[0];
{
var reader = new FileReader();
xlFileName = f.name;
self.fileNameXl1(xlFileName);
console.log(xlFileName);
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date());
var data = e.target.result;
var wb;
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
process_wb(wb);
}
}
reader.readAsArrayBuffer(f);
};
self.fixdata = function(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
return o;
};
self.process_wb = function(wb) {
var output = "";
output = JSON.stringify(to_json(wb), 2, 2);
var parse = JSON.parse(output);
sheetNames = Object.keys(parse);
console.log("this is output");
console.log(sheetNames);
self.xlnames(sheetNames);
if(typeof console !== 'undefined') console.log("output", new Date());
};
self.to_json = function(workbook) {
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
};
self.loadSheetNamesB25 = function(e){
self.xlnames([]);
self.handleFile(e);
};
self.loadSheetNamesB41 = function(e){
self.xlnames1([]);
self.xlnames2([]);
self.handleFile(e);
};
if(xlf1.addEventListener) xlf1.addEventListener('change', self.loadSheetNamesB25, false);
if(xlf2.addEventListener) xlf2.addEventListener('change', self.loadSheetNamesB41, false);

Is there a way to edit this script to overwrite a csv on the server rather than download locally?

I am attempting to use tabletoCSV.js to allow a client to edit their prices in an editable html table and export the changes to overwrite the existing csv file.
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){
text = text.replace(/"/g, '""');
return '"'+text+'"';
};
$(this).each(function(){
var table = $(this);
var caption = $(this).find('caption').text();
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
if(caption==""){
download_link.download = ts+".csv";
} else {
download_link.download = caption+"-"+ts+".csv";
}
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};
As of right now, it simply downloads a generic csv file. Assume the name of the file is "menu.csv".

Word count with javascript

I want to count words from below file types..
['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']/
currently my code reads text files only..
please help me for other file types..
Below is my code..
<script>
$('#file').change( function(event) {
var imgpath=document.getElementById('file');
if (!imgpath.value==""){
var ext = imgpath.value.split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']) != -1) {
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var strings = "";
var contents = e.target.result; alert(contents);
var words = contents.match(/\S+/g).length;
$('#display_file_count').text(words);
}
r.readAsText(f);
}
}else{
alert('file type not supported.');
$('#file').val('');
}
}
});
</script>

Categories