Trying to view sheet after opening spreadsheet with openById() in google sheets - google-apps-script

I have a Google Sheets that has D3.JS, i'm trying to use a specific sheet in the spreadsheet file, since that's where the table is located for the graph i'm trying to show. So far, the openById works but still is unable to locate the specific sheet in the spreadsheet.
function getChartData() {
var ss = SpreadsheetApp.openById("some id");
var sheet = ss.getActiveSheet();
var headings = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
.map(function(heading) {
return heading.toLowerCase();
});
...
}
EDIT: I've tried the following code changes below:
function getChartData() {
var ss = SpreadsheetApp.openById("some id");
var sheet = ss.getSheetByName("Tracker1");
// new code above
var headings = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
.map(function(heading) {
return heading.toLowerCase();
});
Logger.log(headings);
var values = sheet.getRange(3, 1, sheet.getLastRow()-2, sheet.getLastColumn()).getValues();
var data = [];
for (var i = 0; i < values.length; i++) {
var obj = {};
for (var j = 0; j < values[i].length; j++) {
obj[headings[j]] = values[i][j];
}
data.push(obj);
}
return data;
}
EDIT 10/2/18 11:00 PM : I'm still getting null, no error messages, no chart showing in app. I'm sure I'm doing something wrong, even without having getActiveSheet();

Related

google sheets, apps script parsehtml error

this is the complete code,
function extractData() {
var url = "https://www.theopenalliance.com/teams/2023/";
var html = UrlFetchApp.fetch(url).getContentText();
var data = parseHtml(html);
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
if (data.length > 0) {
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (data[i][j].indexOf("http") === 0) {
var button = sheet.getRange(i + 1, j + 1).attachButton({
text: "Link",
url: data[i][j]
});
}
}
}
}
}
function parseHtml(html) {
var startIndex = html.indexOf("<tbody>");
var endIndex = html.indexOf("</tbody>");
var table = html.substring(startIndex, endIndex);
var rows = table.split("<tr>");
var data = [];
for (var i = 1; i < rows.length; i++) {
var cells = rows[i].split("<td");
var row = [];
for (var j = 1; j < cells.length; j++) {
var cell = cells[j];
var linkStartIndex = cell.indexOf("href=");
if (linkStartIndex !== -1) {
var linkEndIndex = cell.indexOf("class");
var link = cell.substring(linkStartIndex + 6, linkEndIndex - 2);
row.push(link);
} else {
row.push(cell.substring(cell.indexOf(">") + 1, cell.indexOf("</td>")));
}
}
data.push(row);
}
return data;
}
however function parseHtml(html) gives an error with this line
var startIndex = html.indexOf("<tbody>");
Anyone has any suggestions? i'm trying to copy and paste tables from the link to a google sheets.
i expected to see every teams numbers and other values (Public links, location etc) in google sheets but nothing shows up. Also i was expecting to see buttons that had links attached to them if the buttons exists, such as github, photos etc. Please check the link and im sure you will have a better idea of im trying to tell. Also please help me fix the code, if possible, copy and edit the code than repost it, i would greatly appreciate it
In your situation, how about using Sheets API? Because I thought that the HTML parser of Sheets API is useful for your situation. When Sheets API is used for your URL, how about the following sample script?
Sample script:
Before you use this script, please enable Sheets API at Advanced Google services.
function myFunction() {
const url = "https://www.theopenalliance.com/teams/2023/"; // This is from your script.
const html = UrlFetchApp.fetch(url).getContentText();
const table = html.match(/<table[\s\S\w]+?<\/table>/);
if (!table) {
throw new Error("Table was not found.");
}
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet().clearContents();
SpreadsheetApp.flush();
const requests = { requests: [{ pasteData: { html: true, data: table[0], coordinate: { sheetId: sheet.getSheetId() } } }] };
Sheets.Spreadsheets.batchUpdate(requests, ss.getId());
}
When this script is run, a table is retrieved from the URL and put it into the active sheet.
References:
Method: spreadsheets.batchUpdate
PasteDataRequest

Trying to create a script for trigger mail based on a condition in google sheets

So this is the script am using, it sends out a blank mail without any content in them. Here I am trying to compare two columns and if the value in one column is great am trying to add the row header to the list which has to be sent out via mail. Can someone help me out pls.
function Mailer1() {
var ss = SpreadsheetApp.openById("");
var sheet = ss.getSheetByName("Today");
var values = sheet.getRange("AD2:AD").getValues();
var value1s = sheet.getRange("AE2:AE").getValues();
var results = [];
for(var i=0;i<values.length;i++)
{
if(values[i]>value1s[i])
{
var value5 = sheet.getRange(i+2,1).getValue();
results.concat(value5);
}
}
MailApp.sendEmail('vinay_narayanan#playshifu.com','Restock Needed At:',results);
};
I'm guessing that the values in 30 and 31 are some sort of quantities and the value in column 1 is a date.
Try doing this:
function Mailer1() {
var ss = SpreadsheetApp.openById("");
var sh = ss.getSheetByName("Today");
var values = sh.getRange(2, 30, sh.getLastRow() - 1).getValues().flat();
var value1s = sh.getRange(2, 31, sh.getLastRow() - 1).getValues().flat();
var results = [];
for (var i = 0; i < values.length; i++) {
if (values[i] > value1s[i]) {
results.push(sh.getRange(i + 2, 1).getValue());
}
}
MailApp.sendEmail('vinay_narayanan#playshifu.com', 'Restock Needed At:', results.join('\n'));
};

Exception Error with Google Script when I tried to use moveActiveSheet

I keep getting "Exception: Service Spreadsheets failed while accessing document with id " while trying to run moveActiveSheet to move a sheet in tab with index 4 to index 1. This just happened very lately. I had been using my code for months before this happened. Does any body is facing the same thing?
My code is below
var ss = SpreadsheetApp.getActiveSpreadsheet();
//==========================================
//Arrange the Sheet
// Store all the worksheets in this array
var sheetNameArray = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
sheetNameArray.push(sheets[i].getName());
};
sheetNameArray.sort();
var sheetName = sheetNameArray[0]; //This tab is currently at index 4
var getSheet = ss.getSheetByName(sheetName);
Logger.log(getSheet.getIndex());
ss.setActiveSheet(getSheet);
ss.moveActiveSheet(1); //Trying to move it to index 1 but exception was thrown
Here is a work-around that worked for me, I loop through the sorted array. I used .batchUpdate from Sheets API. You have to enable it from advanced services first: Resources > Advanced Google Services
function move_sheet_func(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
//==========================================
//Arrange the Sheet
// Store all the worksheets in this array
var sheetNameArray = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
sheetNameArray.push(sheets[i].getName());
};
sheetNameArray.sort();
var sheetName = sheetNameArray[0]; //This tab is currently at index 4
var getSheet = ss.getSheetByName(sheetName);
var sheetsreq = [];
//create requests for each sheet to be moved to its index as sorted
sheetNameArray.forEach(function (name, indx) {
sheetsreq.push({ updateSheetProperties: {
fields: "index, title",
properties: {
index: indx,
title: name,
sheetId: ss.getSheetByName(name).getSheetId()
}
} });
});
var req = { "requests": sheetsreq };
console.log(JSON.stringify(req));
Sheets.Spreadsheets.batchUpdate(req, ss.getId());
}

Google Apps Script mysteriously stops functioning in for loop

I am building a system to copy data from one sheet to another sheet (On a different spreadsheet). It works well, until it is supposed to copy the data. Afterward, it does nothing. No error is thrown, but no alert boxes pop up in the for loop. Here is my code:
function onEdit() {
var sheet = SpreadsheetApp.getActiveSheet();
var master = SpreadsheetApp.openById('13x7AvyYTaocCVBxVZ3ckBjzgxcZfjg9RYM1cE_0VNbU');
var sheets = master.getSheets();
var test = DriveApp.createFile('Test', 'fetching user data...');
var name = test.getOwner().getName();
test.setTrashed(true);
var add = true;
for (var i = 0, n; i < sheets.length; i++) {
n = sheets[i];
if (n.getName() == name) {
add = false;
updateSheet(n, name);
}
}
if (add) {
newSheet(master, name);
}
}
function updateSheet(m, name) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn());
var nr = range.getNumRows();
var nc = range.getNumColumns();
for (var i = 1; i <= nr.length; i++) {
for (var n = 1, s; n <= nc.length; n++) {
s = range.getCell(i, n);
m.getRange(i, n).getCell(1, 1).setValue(s.getValue());
}
}
}
function newSheet(master, name) {
var m = master.insertSheet(name);
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn());
var nr = range.getNumRows();
var nc = range.getNumColumns();
for (var i = 1; i <= nr.length; i++) {
for (var n = 1, s; n <= nc.length; n++) {
s = range.getCell(i, n);
m.getRange(i, n).getCell(1, 1).setValue(s.getValue());
}
}
}
I have searched the code, but can't find anything wrong.
On google documentation at https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#insertsheetsheetname, it says ...
insertSheet(sheetName)
Inserts a new sheet into the spreadsheet with the given name. The new sheet becomes the active sheet.
In your code
function newSheet(master, name) {
var m = master.insertSheet(name); // after calling this function m becomes the active sheet
var sheet = SpreadsheetApp.getActiveSheet(); // you've assigned m to sheet
I would recommend using getSheetByName('SheetName').
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");
Refer to this link https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename
The obvious answer (Thanks #Rubén)
In the for loop, it says nc.length and nr.length. Both getNumRows and getNumColumns return numbers. Since these are integers, .length is not necessary.

Google App Script - getCommenter

I'm brand new to Google Apps Script, and I'm trying to create a simple spreadsheet that will allow me to share files by user email through a single spreadsheet.
I have written the following script, which will allow me to add editors and viewers, but not commenters.
I keep getting an error that states that the function addCommenter cannot be found in object spreadsheet.
function shareSheet () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.toast('Updating access level...');
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var range1 = sheet.getRange (3,1, lastRow,9);
var data = range1.getValues();
for (var i= 0; i < data.length; i++) {
var row = data [i];
var accessLevel = row [5];
var values = row [8];
var ss2 = SpreadsheetApp.openById(values);
var values2 = row [4];
// Add new editor
if (accessLevel == 'Edit') {
var addEditors = ss2.addEditor(values2);
}
// Add new viewer
if (accessLevel == 'View'){
var addViewers = ss2.addViewer(values2);
}
// Add new commenter
if (accessLevel == 'Comment') {
var addCommenters = ss2.addCommenter(values2);
}
}
}
The Spreadsheet object does not support the addCommentor() method. You should use DriveApp service instead.
DriveApp.getFileById(id).addCommenter(emailAddress)