I'm writing a client side method, that creates an array of objects.I open an existing excel to write the values from the array. I get the values using getProperty and store in a variable.
When I try to write those in the excel, I get "event handler failed with message";" ".
Code:
var getItemtoExcel = document.thisItem.newItem("ToExcel", "get");
getItemtoExcel = getItemtoExcel.apply();
var arrToExcel = Array();
for (var j = 0; j < getItemtoExcel.getItemCount(); j++) {
var gotItemForExcel = getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Excel.Workbooks.Open("C:\\test.xls");
var offset = 0;
var row = 2;
for (var c = 0; c < arrToExcel.length; c++) {
var createExcel = arrToExcel[c];
var Number = createExcel.getProperty("nb");
var Type = createExcel.getProperty("type");
var Code = createExcel.getProperty("code");
var State = createExcel.getProperty("state");
Excel.Worksheets("sheet11").Range("A" & row + 1 + offset).Value = Number;
Excel.Worksheets("sheet11").Range("B" & row + 1 + offset).Value = Type;
Excel.Worksheets("sheet11").Range("C" & row + 1 + offset).Value = Code;
Excel.Worksheets("sheet11").Range("D" & row + 1 + offset).Value = State;
row = row + 1;
}
offset = offset + 1;
return this;
document.thisItem.newItem() is from ARASPLM. Its the standard used to call an ItemType(Item) in ARAS
If you have an opportunity to use SheetJS, it's pretty straightforward
Firstly, Install xlsx package npm install --save xlsx
const XLSX = require('xlsx')
// array of objects to save in Excel
let binary_univers = [{'name': 'Hi','value':1},{'name':'Bye','value':0}]
let binaryWS = XLSX.utils.json_to_sheet(binary_univers);
// Create a new Workbook
var wb = XLSX.utils.book_new()
// Name your sheet
XLSX.utils.book_append_sheet(wb, binaryWS, 'Binary values')
// export your excel
XLSX.writeFile(wb, 'Binaire.xlsx');
i think using this you can get what you want but you need to pass the your Object's value with this that i have mentioned here as (Your Data(Object))
window.open('data:application/vnd.ms-excel,' + **(Your Data(Object))**);
here i'm providing simple code for get data into excel format with jquery
SAMPLE DEMO
Thanks for all your suggestions on this question.
I have done with exporting the array into a .csv file successfully.
Here's the code, for others who will need.
var getItemtoExcel=this.newItem("MyForm", "get");
getItemtoExcel=getItemtoExcel.apply();
var arrToExcel = Array();
for (var j=0; j<getItemtoExcel.getItemCount(); j++)
{
var gotItemForExcel=getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\REPORT.csv", true);
var title="Report";
s.WriteLine(title);
var header="Number" + ";" + "Type" + ";" + "Code" + ";" + "Created On" + ";" + "State" + '\n' ;
s.WriteLine(header);
for (var c=0; c<arrToExcel.length; c++){
var createExcel = arrToExcel[c];
var Number =createExcel.getProperty("nb");
var Type=createExcel.getProperty("type");
if(Type===undefined){Type="";}
var Code=createExcel.getProperty("code");
if(Code===undefined){Code="";}
var Date=createExcel.getProperty("created_on");
var State=createExcel.getProperty("created_by_id/#keyed_name");
var value=Number + ";" + Type + ";" + Code + ";" + Date + ";" + State;
s.WriteLine(value);
}
s.Close();
alert("Report Saved as C:\\REPORT.csv");
return this;
Related
I have Google Apps Script which inputs events into my google calendar from a spreadsheet. Anyone know how to have the script set a row's background color to green & last column value to "complete" only if it's been ran through the loop?
Currently I have it just setting the full range to these parameters, but would like to prevent certain rows from being included if the last column is equal to "Invalid".
function inputEvents() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("B1").getValue();
var calendar = CalendarApp.getCalendarById(calendarId)
var lr = spreadsheet.getLastRow();
var count = spreadsheet.getRange("A3:AF"+lr+"").getValues();
for (x=0; x<count.length; x++) {
var events = count[x];
var name = events[2];
var phone = events[3];
var email = events[4];
var title = events[5];
var startTime = events[6];
var endTime = events[7];
var description = events[8];
var location = events[9];
var eventId = events[31];
var contactHeader = "CONTACT:";
var descriptionHeader = "DESCRIPTION:";
var complete = "Complete";
var invalid = "Invalid";
var info =
contactHeader.bold() + "\n"
+ name + "\n"
+ phone + "\n"
+ email + "\n"
+ "\n" + descriptionHeader.bold() + "\n"
+ description;
var options = {
'guests' : email,
'description': info,
'sendInvites': 'True',
'location': location,
}
if (eventId != complete && eventId != invalid){
calendar.createEvent(title, startTime, endTime, options);
spreadsheet.getRange("AF3:AF"+lr+"").activate().setValue('Complete');
spreadsheet.getRange("A3:AF"+lr+"").activate().setBackground('#d9ead3');
}
}
}
You're using the setValue and setBackground methods to the entire range, you need to apply them only to the range you're interested in, try setting a currentRow variable and change the range you're getting inside your if statement, like this:
var currentRow = 3 + x;
if (eventId != complete && eventId != invalid){
calendar.createEvent(title, startTime, endTime, options);
spreadsheet.getRange("AF" + currentRow).setValue('Complete');
spreadsheet.getRange("A"+ currentRow + ":AF" + currentRow).setBackground('#d9ead3');
}
I'm trying to send a telegram message to myself, every morning, with a different quote that I have listed in a Google Sheet. I wrote some code that adds messages to the list, but I can't seem to generate a random row from the list to send daily.
var token = "TOKEN";
var telegramAPI = "https://api.telegram.org/bot" + token;
var webAppAPI = "https://script.google.com/macros/s/GOOGLE_WEB_APP_ADDRESS";
var ssId = "SPREADSHEET_ID";
function getMe() {
var url = telegramAPI + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramAPI + "/setWebhook?url=" + webAppAPI;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramAPI + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Test Data" + JSON.stringify(e,null,4));
}
function doPost(e) {
Logger.log(e);
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var what = data.message.text.split("-")[0]
var who = data.message.text.split("-")[1]
var id = data.message.chat.id;
var name = data.message.chat.first_name;
var response = "Hi " + name + ", this quote has been added to your database: " + text;
sendText(id,response);
SpreadsheetApp.openById(ssId).getSheets()[1].appendRow([new Date(),id,name,text,response,what,who]);
All of this works fine. I added a query that pulls them over to my Quote sheet from my Telegram Feed sheet, that I'll put here to help someone:
=IFERROR(QUERY('Telegram Feed'!$G$1:$G$98,"",-1),"Error")
Now that I'm pulling in quotes, I want to generate a random one from the list and schedule it to send to myself on a daily basis. I've included what I've tried below, but I can't seem to figure out what I'm doing wrong.
The randomizer is partially working, but seems to be grabbing all of the content, which I need to refactor to say something along the lines of:
message = f"{quote} + ' - ' + {author}"
Randomizer:
function randomizer() {
var ssa = SpreadsheetApp.openById(ssId);
var ss = ssa.getSheetByName('Quotes');
var range = ss.getRange(1,1,ss.getLastRow(), 2);
var data = range.getValues();
for(var i = 0; i < data.length; i++)
{
var j = Math.floor(Math.random()*(data[i].length));
var element = data[i][j];
ss.getRange(i+1, 6).setValue(element);
Logger.log(element);
}
}
Up until this point, it mostly works (even though I need to figure out how to fix the randomizer function as mentioned above. It's when I try to send a random message from the script to Telegram that I run into problems.
function sendQuote(what,who) {
var data = randomizer();
var dataJSON = JSON.parse(data.postData.contents);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID_NUM' + "&text=" + what + " - " who;
}
I'm getting nothing back. Anyone know what I'm doing wrong?
EDIT:
I followed the suggestions from Дмитро-Булах & carlesgg97, and I refactored a bunch of my randomize code to give me a quote and author. For some reason, I'm now getting the error "TypeError: Cannot read property "postData" from undefined.: from the line that reads var dataJSON = JSON.parse(data.postData.contents);
Does anyone know why this is happening?
I'll close the issue within 24hrs regardless. Thanks for the help everybody!
function sendQuote(quote,author) {
var data = randomize();
var dataJSON = JSON.parse(data.postData.contents);
var encodedText = encodeURIComponent(quote + " - " + author);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID' + "&text=" + encodedText;
UrlFetchApp.fetch(url);
}
function randomize() {
var sss = SpreadsheetApp.openById(ssId);
var ss = sss.getSheetByName('Quotes');
var length = ss.getLastRow();
var overshoot = 97 //monitor for changes as list size increases
var true_length = length-overshoot;
var line = (Math.random() * ((true_length - 2) + 1)) + 2;
var quote_cell = ss.getRange(line,2);
var quote = quote_cell.getValue();
var author_cell = ss.getRange(line,1);
var author = author_cell.getValue();
Logger.log(quote + " - " + author);
}
Seems like you may be having two different problems:
You are not encoding the text as URL-safe. To safely append data (in this case the text URL Query string parameter) to your URL, you should use encodeURIComponent().
You don't seem to actually be sending the request. Did you miss the UrlFetchApp.fetch() call?
See below an example that fixes both issues:
function sendQuote(what,who) {
var data = randomizer();
var dataJSON = JSON.parse(data.postData.contents);
var encodedText = encodeURIComponent(what + " - " + who);
var url = telegramAPI + "/sendMessage?chat_id=" + 'CHAT_ID_NUM' + "&text=" + encodedText;
UrlFetchApp.fetch(url);
}
I am fairly new to the Javascript language.
I am trying to make a clicker game (not so hard). The game is working but I am trying to make a save method for the game.
Instead of cookies I decided to have the game make its own code where the user can copy and paste it the next time they get on the game.
So the save method works but when I try to have the game load the code it doesn't quite do it right.
Instead of grabbing the values before the commas it grabs the letters of the word I use as a checker.
Is there a way I can fix this?
Here's my code:
var shovel = 0;
var miner = 0;
var loaders = 0;
var drill = 0;
var tnt = 0;
var minecart = 0;
var bulldozer = 0;
var trucks = 0;
var manager = 0;
var cost1 = 10;
var cost2 = 200;
var cost3 = 350;
var cost4 = 500;
var cost5 = 600;
var cost6 = 800;
var cost7 = 2500;
var cost8 = 6000;
var cost9 = 100000;
var cash = 0;
var cashRate = 1000;
//-- SAVE GAME --
function save() {
var save = "";
var data = cash + "," + cashRate + "," + shovel + "," + miner + "," + loaders + "," + drill + "," + tnt + "," + minecart + "," + bulldozer + "," + trucks + "," + manager + "," + cost1 + "," + cost2 + "," + cost3 + "," + cost4 + "," + cost5 + "," + cost6 + "," + cost7 + "," + cost8 + "," + cost9;
save += "CoalMinerGame=" + data;
var finalSave = encode(save);//Encoding/Decoding is done using the Base64 Code
prompt("Keep this somewhere you'll remember!", finalSave);
}
function load() {
var code = prompt("Paste the save code below!", "");
if (code != "") {
var load = decode(code);
if (load.includes("CoalMinerGame=")) {
load.split("CoalMinerGame=");
//load[0] = blank
cash = load[1];
cashRate = load[2];
shovel = load[3];
miner = load[4];
loaders = load[5];
drill = load[6];
tnt = load[7];
minecart = load[8];
bulldozer = load[9];
trucks = load[10];
manager = load[11];
cost1 = load[12];
cost2 = load[13];
cost3 = load[14];
cost4 = load[15];
cost5 = load[16];
cost6 = load[17];
cost7 = load[18];
cost8 = load[19];
cost9 = load[20];
updateWorkers();
alert("Save Successfully Loaded!");
} else {
alert("Not a valid save code!");
}
} else {
alert("You must enter a save code to get your game back!");
}
}
Save
Load
I see two mistakes :
The load.split() function does not modify load but returns an array instead, an array that you should store in another variable.
You should also split once again the resulting string on commas to separate your different values.
Hope it helps!
Oh man, this code is giving me a pain :).
What about use some native functions for whole objects so you dont have to manually serialize it and deserialize it?
This code
const myObject = {
some: 'fields',
even: {
nested: 'fields',
},
};
const stringified = JSON.stringify(myObject);
console.log(stringified);
const unstringified = JSON.parse(stringified);
console.log(unstringified);
Is having this output
{"some":"fields","even":{"nested":"fields"}}
{ some: 'fields', even: { nested: 'fields' } }
You can also use base64 steps to code and decode
The JSON.stringify take JS object and create pure string which contains JSON inside.
Then when you want to take JSON and create object from it, you can just JSON.Parse, which expects string.
I echo the sentiment to use JSON. My example below might require some refactoring in the game code but would be cleaner. To access the variable cash you would just use gameData.cash where you currently are using the cash var.
var gameData = {
cash: 0,
cashRate:0,
shovel:0,
miner:0,
loaders:0,
drill:0,
tnt:0,
minecart:0,
bulldozer:0,
trucks:0,
manager:0,
cost1:10,
cost2:200,
cost3:350,
cost4:500,
cost5:600,
cost6:800,
cost7:2500,
cost8:6000,
cost9:100000
}
function save(){
var dataToSave = CoalMinerGame: {
cash: cash,
cashRate:cashRate,
shovel:shovel,
miner:miner,
loaders:loaders,
drill:drill,
tnt:tnt,
minecart:minecart,
bulldozer:bulldozer,
trucks:trucks,
manager:manager,
cost1:cost1,
cost2:cost2,
cost3:cost3,
cost4:cost4,
cost5:cost5,
cost6:cost6,
cost7:cost7,
cost8:cost8,
cost9:cost9
}
var finalSave = JSON.Stringify(dataToSave)
finalSave = encode(finalSave)
prompt("Keep this somwhere you'll remember!", finalSave)
}
function load(){
var code = prompt("Paste the save code below!", "")
var load = decode(code)
if (code != ""){
gameData = load;
updateWorkers();
alert("Save Successfully loaded!")
} else {
alert("You must enter a save code to get your game back!")
}
}
I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});
My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}
tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;