I have a HTML File that upload a TSV File and display it in console as an array. here is the code.
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
// By tabs
var tabs = lines[line].split('\\t');
for(var tab = 0; tab < tabs.length; tab++){
console.log(tabs[tab]);
}
}
};
reader.readAsText(file);
};
<input type="file" name="file" id="file">
now here is my code.gs
function doGet(e){
var html = HtmlService.createHtmlOutputFromFile("index");
return html;
}
My question is how can I pass the array from the html file to code.gs? maybe a sample Logger.log will be okay form me. My target here is to upload that array in google sheet. TYSM
How about following modification? When it sends the values on html to GAS, you can achieve this using google.script.run.
In this modifed sample, the array is sent to work() on GAS, and the array data is imported to Spreadsheet.
Modified Script :
index.html
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var ar = []; // <--- added
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
// By tabs
var tabs = lines[line].split('\t'); // <--- modified from '\\t' to '/t'
for(var tab = 0; tab < tabs.length; tab++){
console.log(tabs[tab]);
}
ar.push(tabs); // <--- added
}
google.script.run.work(ar); // <--- added
};
reader.readAsText(file);
};
code.gs
function doGet(e){
var html = HtmlService.createHtmlOutputFromFile("index");
return html;
}
function work(res){
var ss = SpreadsheetApp.getActiveSheet();
ss.getRange(1,1,res.length,res[0].length).setValues(res);
}
Input
a1 b1 c1
a2 b2 c2
a3 b3 c3
Output
If I misunderstand your question, I'm sorry.
Related
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=
I followed the demo here:
https://github.com/SheetJS/js-xlsx/tree/master/demos/electron
I'm able to drag an excel file into my electron app.
The documentation says, you can access every cell with:
for(var R = range.s.r; R <= range.e.r; ++R) {
for(var C = range.s.c; C <= range.e.c; ++C) {
var cell_address = {c:C, r:R};
/* if an A1-style address is needed, encode the address */
var cell_ref = XLSX.utils.encode_cell(cell_address);
}
}
How do I use it with my Code below? I got the content of the file stored in my test variable, but I'm not able to access it. The documentation lack of information there.
var do_file = (function() {
return function do_file(files) {
var f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
data = new Uint8Array(data);
test = XLSX.read(data, {type: 'array'});
console.log(test);
};
reader.readAsArrayBuffer(f);
};
})();
I got no clue how to start with it, thanks in advance
Here it goes:
var do_file = (function() {
return function do_file(files) {
var f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
data = new Uint8Array(data);
//process_wb(XLSX.read(data, {type: 'array'}));
/* read the file */
var workbook = XLSX.read(data, {type: 'array'}); // parse the file
var sheet = workbook.Sheets[workbook.SheetNames[0]]; // get the first worksheet
/* loop through every cell manually */
var range = XLSX.utils.decode_range(sheet['!ref']); // get the range
for(var R = range.s.r; R <= range.e.r; ++R) {
for(var C = range.s.c; C <= range.e.c; ++C) {
/* find the cell object */
console.log('Row : ' + R);
console.log('Column : ' + C);
var cellref = XLSX.utils.encode_cell({c:C, r:R}); // construct A1 reference for cell
if(!sheet[cellref]) continue; // if cell doesn't exist, move on
var cell = sheet[cellref];
console.log(cell.v);
};
reader.readAsArrayBuffer(f);
};
})();
Generally you can access a cell with standard excel coordinates like
console.log(sheet['My Sheet Name']['B3'].v);
See the full data types here: https://github.com/SheetJS/sheetjs/blob/master/README.md#cell-object
I was wondering if it is possible to get this right. I am using a Jquery cropping tool (cropit). I am trying to put multiple file inputs into several cropper instances at once. Unfortunately it doesnt work that well.
For example, if I upload three images, the first two croppers are empty and the last one gets one of the images randomly. Here is the function:
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var reader = new FileReader();
reader.onload= function(e){ $('#image-cropper'+count).cropit('imageSrc', e.target.result);};
reader.readAsDataURL(file);
}
}
Figured it out!
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var croper = $('#image-cropper'+count);
var reader = new FileReader();
reader.onload= (function (yo) {return function(e){ yo.cropit('imageSrc', e.target.result);}})(croper);
reader.readAsDataURL(file);
}
}
I have a function that is loading a user selected file using the Javascript File API, but I want to limit the type of file that can be loaded. Is this possible and how do I go about doing it? So for example, I only want the user to be able to load a DAT file. Here's my function loading the file.
function readFile(file){
var reader = new FileReader();
var holder;
var holderArray = [];
var fileArray = [];
reader.readAsText(file, "UTF-8");
reader.onload = function(){
file = reader.result;
file = file.split(/\s+/g);
formatFile(holderArray, 3, holder, file, fileArray);
for(var i = 0; i < 2; i++){
formatFile(holderArray, 1, holder, file, fileArray);
}
for(var i = 0; i < 2; i++){
formatFile(holderArray, 2, holder, file, fileArray);
}
var meh = file.length / fileArray.length;
for(var i = 0; i < meh; i++){
formatFile(holderArray, 5, holder, file, fileArray);
}
fileArray.pop();
plume = new Plume(fileArray[0], fileArray[4], fileArray[3]);
$("#eventDate").val(plume.dateTime);
$("#eventLat").val(plume.startLat);
$("#eventLon").val(plume.startLong);
$("#eventDictionary").val(plume.dict);
$("#eventSymbol").val(plume.symbol);
fileArray = fileArray.splice(5);
plume.graphic = fileArray;
}
}
$("#load").on("click", function(){
$("#eventNameInput").val("");
var selectedFile = $("#selectedFile");
selectedFile = selectedFile[0].files[0];
if(selectedFile){
readFile(selectedFile);
$("#fileDetails").show();
}
})
Sure. You can declare MIME type in "accept" attribute For example this input will upload images :
<input type="file" name="img" accept="image/*">
for .dat you can do this (.dat is unknown MIME type):
<input type="file" name="img" accept=".dat">
I want to load a *.csv file from a path which the user can choose.
The path I get: C:\\Users\\...
But the $.get method can't read this path. What does the path have to look like?
$.get(pathAndFile, function (data) {...
If you wanted to read CSV data in JavaScript from a computer you would need to instruct the user to select the file (there is no way around this, with the possible exception of a virus). However once a user selected a file you can read and parse CSV data with a small amount of JavaScript like this (demo)
With this HTML:
<input type="file" id="file" name="file" />
<table id="rows"></table>
And this JavaScript:
var output = $('#rows');
$('#file').on('change', function(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process text files.
if (!f.type.match('text/.*')) {
alert('Unsupported filetype:'+f.type);
continue;
}
var reader = new FileReader();
reader.onloadend = function(evt) {
var rows, row, cols, col, html;
if (evt.target.readyState == FileReader.DONE) {
output.empty();
rows = evt.target.result.match(/[^\r\n]+/g);
for(row = 0; row < rows.length; row++) {
cols = rows[row].split(',');
html = '<tr>';
for(col = 0; col < cols.length; col++) {
html += '<td>'+cols[col]+'</td>';
}
html += '</tr>';
output.append(html);
}
}
};
// Read in the text file
reader.readAsBinaryString(f);
}
});
You can generate an HTML table from the contents of a CSV file (this is based on this excellent site)
function getFile(fileToRead) {
var reader = new FileReader();
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
createChart(csv);
}