How to change the Height of Multiple rows at Once? - google-apps-script

How do I change the height of multiple rows at once via Google Apps Script?
Attempt:
function resizeHeight() {
  var s = SpreadsheetApp,
      ui = s.getUi(),
  sh = s.getActiveSheet(),
curntRow = s.getActiveRange().getRow(),
rowsMany = s.getActiveRange().getNumRows(),
autoRangeRows = s.getActiveRange().getA1Notation().replace(/[a-z]/gi,""),
  getVal = ui.prompt('⿱⇕', 'Change the height of row❓   Cancel. Back to default❗  (21)', ui.ButtonSet.OK_CANCEL),
  Btn = getVal.getSelectedButton(), Txt = getVal.getResponseText();
for (var i=curntRow; i<=rowsMany+1; i++) {
if (Btn == 'OK') {
if (autoRangeRows.search(":") == -1) {sh.setRowHeight(curntRow, Txt);}
else {sh.setRowHeight(i, Txt);}
}
if (Btn == 'CANCEL') {
if (autoRangeRows.search(":") == -1) {sh.setRowHeight(curntRow, 21);}
else {sh.setRowHeight(i, 21);}
}
}
}
Problem:
The script is not very effective they only work on the part or a few rows but not on all rows can be implemented.

This function works: You just have to pick an active range to select the rows that you want to change the height of and then give it a height in pixels in the prompt.
function changeRowHeight()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getActiveSheet()
var rng=sht.getActiveRange();
var row=rng.getRow();
var numrows=rng.getNumRows();
var resp=SpreadsheetApp.getUi().prompt('Get Row Height', 'Enter Row Height in Pixels', SpreadsheetApp.getUi().ButtonSet.OK);
var height = Number(resp.getResponseText());
for(var i=0;i<numrows;i++)
{
sht.setRowHeight(row + i, height)
}
}

Related

Tabulator - Dependent Select with Custom Editor

I need to show the list in the select box based on the another input.
On click on the SubCategory column, its showing the selected value in the dropdown. But its not showing in the table.
You can see the table in the below image. First image its not showing the data in the display, in the second image its showing the value selected
Anything missed. Any help please..
Attached the working code.
var comboEditor = function (cell, onRendered, success, cancel, editorParams) {
//Getting the other select value, based on the value this select need to show the list
let otherCellValue = cell.getData().ForumCourt;
cboData = []; //Store last values based on another cell value
var currentlyAdded = [];
var editor = document.createElement("select");
arrayOfValues2 = caselocationData.filter(function(r){return true;});
var filteredArrayOfValues = arrayOfValues2.filter(function(r){ return r[0]=== otherCellValue});
// addUniqueOptionsToDropdownList(select2_Sub, filteredArrayOfValues,1);
filteredArrayOfValues.forEach(function(r){
if(currentlyAdded.indexOf(r[0]) === -1) {
currentlyAdded.push(r[1]);
var item = {};
item.key = r;
item.name = r[1];
cboData.push(item);
}
});
for (var i = 0; i < cboData.length; i++) {
var opt = document.createElement('option');
opt.value = cboData[i].key;
opt.innerHTML = cboData[i].name;
editor.appendChild(opt);
}
editor.style.padding = "0px";
editor.style.width = "100%";
editor.style.boxSizing = "border-box";
editor.value = cell.getValue();
onRendered(function () {
editor.focus();
editor.style.css = "100%";
});
function successFunc() {
success(editor.value);
}
editor.addEventListener("change", successFunc);
editor.addEventListener("blur", successFunc);
return editor;
};

Using an array or the map function to improving on a nested loop performance to change/substitute cell colours in googlescript

Hi still a relative newbie here...I've got some nested loops which cycle through each cell in a sheet range looking for a background color and if it finds a match then the background colour is changed. Yes - I am sorry for this approach(!). Am thinking I must be able to get the background colours via an array and then apply a transformation to the array using .map(?) but have experimented and haven't worked it out so far. Other examples on S/O don't show a substitute approach that I have been able to apply across. Any advice/thoughts would be greatly appreciated. Thanks
function myColorFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
for (var y = 1; y < 70; y++){
for (var x = 1; x < 50; x++){
var bghex = ss.getRange(y,x).getBackground();
if(bghex == '#001d66') { //occasional cell colour
ss.getRange(y,x).setBackground("#027db6");
}
else if (bghex == '#00288b') { //main bkgrnd colour
ss.getRange(y,x).setBackground("#0297db");
}
else if (bghex == '#fbf025') { //yellow fill-in
ss.getRange(y,x).setBackground("#fdd201");
}
}
Logger.log('Line ' + y + ' complete');
}
}
My approach would be like this, using a nested .map() function and using getBackgrounds() first to populate the 2D Array of cell colors, then replacing it using an if-else statement, from there you can use setBackgrounds() to apply the changes to the whole range.
function myColorFunction2() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
var range = ss.getRange(1,1,70,50);
var bghex = range.getBackgrounds();
bghex.map(row => row.map((elem,index) => {
if(elem == '#001d66'){
row[index] = '#027db6';
}
else if (elem == '#00288b') {
row[index] = '#0297db';
}
else if (elem == '#fbf025') {
row[index] = '#fdd201';
}
}));
range.setBackgrounds(bghex);
Logger.log(bghex);
}
Output:
This amount took about only 1 second runtime duration:
Ref:
setBackgrounds()
getBackgrounds()
Array.prototype.map()
Instead of using getBackground(), use getBackgrounds(), this way instead of getting individual values, you get an array where you can apply the map() function.
Here is an example replacing red backgrounds.
function myColorFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My Sheet");
var range = sheet.getRange("A1:B10");
var backgrounds = range.getBackgrounds(); // Return 2D arr
// Applies map() function on each row
for (let i = 0; i < backgrounds.length; i++) {
backgrounds[i] = backgrounds[i].map(function(item) { return item == "#ff0000" ? "#0000ff" : item; });
}
// Set new backgrounds
range.setBackgrounds(backgrounds);
}

Google Apps Script: insert and update texts by ID/name in Google Docs

I want to be able to insert, in Google Docs using Google Apps Script, custom texts with a given ID, so that afterwards I'd be able to update them (any number of times). The insertion should work with cursor placement as well as with replacing any selected elements.
I have a code that works pretty well for this (based partly on this answer), see below. I use "named ranges" for IDing the inserted/updated texts. The only problem is, when I have several such inserted texts immediately next to each other, and I update both repeatedly, suddenly the preceding one "absorbs" the following one (i.e., deletes it). So clearly it is a problem of the named ranges somehow expanding into each other, but I cannot figure out why.
// function for inserting text
insertAny = (textToInsert, textName = null, range = null) => {
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
var rangeBuilder = null;
if (cursor && (range === null)) {
// Attempt to insert text at the cursor position. If the insertion returns null, the cursor's
// containing element doesn't allow insertions, so show the user an error message.
var cElement = cursor.insertText(textToInsert);
if (!cElement) {
textName = null
DocumentApp.getUi().alert('Cannot insert text here.');
} else {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(cElement);
}
} else {
var selection;
if (range === null) {
selection = DocumentApp.getActiveDocument().getSelection();
} else {
selection = range;
}
if (!selection) {
textName = null
DocumentApp.getUi().alert('Insertion omitted: A cursor placed in the text or a selected text is needed to indicate the position of the insertion.');
} else {
var elements = selection.getRangeElements();
var replace = true;
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var tElement = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
var text = tElement.getText().substring(startIndex, endIndex + 1);
tElement.deleteText(startIndex, endIndex);
if (replace) {
tElement.insertText(startIndex, textToInsert);
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(tElement, startIndex, startIndex + textToInsert.length - 1);
}
replace = false;
}
} else {
var eElement = elements[i].getElement();
// if not specified as "any", throws type errors for some reason
if (replace && eElement.editAsText) {
eElement.clear().asText().setText(textToInsert);
replace = false;
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(eElement);
}
} else {
if (replace && i === elements.length - 1) {
var parent = eElement.getParent();
parent[parent.insertText ? 'insertText' : 'insertParagraph'](parent.getChildIndex(eElement), textToInsert);
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(eElement);
}
replace = false; //not really necessary since it's the last one
}
eElement.removeFromParent();
}
}
}
}
}
if (textName !== null && rangeBuilder !== null) {
doc.addNamedRange(textName, rangeBuilder.build());
}
}
// function for updating text
const updateNamedRange = (textName, newText) => {
var doc = DocumentApp.getActiveDocument();
var myNamedRanges = doc.getNamedRanges(textName);
for (var i = 0; i < myNamedRanges.length; i++) {
var range = myNamedRanges[i].getRange();
insertAny(newText, textName, range);
}
}
Any ideas (or better solutions)?
Okay, so it seems that the reason is that if I insert text immediately next to a named range, it will automatically belong to that range. (Hence subsequent updates affected these unrelated parts too.)
My really hacky solution is to temporarily insert a placeholder character to separate the new text from any potential named ranges... It makes me laugh, but nothing else I tried works as well. This seems to be robust to all the tricky scenarios I can think of. My final code is below.
const insertAny = (textToInsert, textName = null, range = null) => {
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
var rangeBuilder = null;
if (cursor && (range === null)) {
// Attempt to insert text at the cursor position. If the insertion returns null, the cursor's
// containing element doesn't allow insertions, so show the user an error message.
var cElement = cursor.insertText(textToInsert);
if (!cElement) {
textName = null
DocumentApp.getUi().alert('Cannot insert text here.');
} else {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(cElement);
}
} else {
var selection;
if (range === null) {
selection = DocumentApp.getActiveDocument().getSelection();
} else {
selection = range;
}
if (!selection) {
textName = null
DocumentApp.getUi().alert('Insertion omitted: A cursor placed in the text or a selected text is needed to indicate the position of the insertion.');
} else {
var elements = selection.getRangeElements();
if (range !== null) {
elements.length = 1;
}
var replace = true;
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var tElement = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
var text = tElement.getText().substring(startIndex, endIndex + 1);
if (replace) {
tElement.insertText(endIndex + 1, 'x');
tElement.deleteText(startIndex, endIndex);
tElement.insertText(startIndex + 1, textToInsert);
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(tElement, startIndex + 1, startIndex + 1 + textToInsert.length - 1);
}
replace = false;
tElement.deleteText(startIndex, startIndex);
} else {
tElement.deleteText(startIndex, endIndex);
}
} else {
var eElement = elements[i].getElement();
// if not specified as "any", throws type errors for some reason
if (replace && eElement.editAsText) {
eElement.clear().asText().setText(textToInsert);
replace = false;
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(eElement);
}
} else {
if (replace && i === elements.length - 1) {
var parent = eElement.getParent();
parent[parent.insertText ? 'insertText' : 'insertParagraph'](parent.getChildIndex(eElement), textToInsert);
if (rangeBuilder === null) {
rangeBuilder = doc.newRange();
rangeBuilder.addElement(eElement);
}
replace = false; //not really necessary since it's the last one
}
eElement.removeFromParent();
}
}
}
}
}
if (textName !== null && rangeBuilder !== null) {
doc.addNamedRange(textName, rangeBuilder.build());
}
}
const updateNamedRange = (textName, newText) => {
var doc = DocumentApp.getActiveDocument();
var myNamedRanges = doc.getNamedRanges(textName);
for (var i = 0; i < myNamedRanges.length; i++) {
var range = myNamedRanges[i].getRange();
myNamedRanges[i].remove();
insertAny(newText, textName, range);
}
}

How can I parse html table inside a script respecting merged cells

This header is contained in a js file https://www.portaldefinancas.com/js-tx-ctb/th-cdib.js
document.write(""),document.write('</p></caption><thead><tr><th rowspan="4">Mês de<br>Referência</th><th colspan="7">Taxas - %</th></tr><tr> <th rowspan="3">Mensal</th><th colspan="4">Anualizada</th><th colspan="2">Acumulada</th></tr><tr> <th colspan="2">Ano de<br>252 dias<br> úteis</th><th colspan="2">Ano de<br>365/366 dias<br>corridos</th><th rowspan="2">No ano</th><th rowspan="2">Em <br>12 meses</th></tr><tr><th>Dias</th><th> Taxa</th><th>Dias</th><th> Taxa</th></tr></thead><tbody>');
How can I parse the headers respecting the merged rows and merged columns. The script I use today is
function getHeaders(url) {
var source = UrlFetchApp.fetch(url).getContentText()
source = source.split('document')[2]
var table = '<table><tr><th ' + source.match(/(?<=<th ).*(?=th>)/g) + 'th></tr></table>'
table=table.replace(/ê/g,'ê').replace(/ú/g,'ú').replace(/<br>/g,'\n')
var doc = XmlService.parse(table);
var rows = doc.getDescendants().filter(function(c) {
var element = c.asElement();
return element && element.getName() == "tr";
});
var data = rows.slice(0).map(function(row) {
return row.getChildren("th").map(function(cell) {
return cell.getValue();
});
});
return data;
}
but it doesn't respect merged areas. Thanks for any help !
Since intellectual exercises is my my drug of choice... I can't help it. Here is the possible solution. It works to a degree but it shows little the traits of lofty style of coding:
function main() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = getHeaders();
data = handle_rowspans(data);
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}
function getHeaders(url) {
// var source = UrlFetchApp.fetch(url).getContentText()
// source = source.split('document')[2]
var source = `<thead><tr><th rowspan="4">Mês de<br>Referência</th><th colspan="7">Taxas - %</th></tr><tr> <th rowspan="3">Mensal</th><th colspan="4">Anualizada</th><th colspan="2">Acumulada</th></tr><tr> <th colspan="2">Ano de<br>252 dias<br> úteis</th><th colspan="2">Ano de<br>365/366 dias<br>corridos</th><th rowspan="2">No ano</th><th rowspan="2">Em <br>12 meses</th></tr><tr><th>Dias</th><th> Taxa</th><th>Dias</th><th> Taxa</th></tr></thead><tbody>`;
source = handle_colspans(source);
table = '<table><tr><th ' + source.match(/(?<=<th ).*(?=th>)/g) + 'th></tr></table>';
table = table.replace(/ê/g, 'ê').replace(/ú/g, 'ú').replace(/<br>/g, '\n');
var doc = XmlService.parse(table);
var rows = doc.getDescendants().filter(function (c) {
var element = c.asElement();
return element && element.getName() == "tr";
});
var data = rows.slice(0).map(function (row) {
return row.getChildren("th").map(function (cell) {
return cell.getValue();
});
});
return data;
}
function handle_colspans(table) {
return table.split('</tr>').map(r => add_cells_in_row(r)).join('</tr>');
function add_cells_in_row(row) {
var cells = row.split('</th>');
for (var i in cells) {
if (/colspan/.test(cells[i])) {
var colspan = cells[i].replace(/.*colspan="(\d+).*/, '$1');
cells[i] += '{col' + colspan + '}';
cells[i] = [cells[i], ...(new Array(+colspan - 1).fill('<th>'))];
}
if (/rowspan/.test(cells[i])) {
var rowspan = cells[i].replace(/.*rowspan="(\d+).*/, '$1');
cells[i] += '{row' + rowspan + '}';
}
}
return cells.flat().join('</th>')
}
}
function handle_rowspans(array) {
for (var row in array) {
for (var col in array[row]) {
if (/\{row/.test(array[row][col])) {
var rowspan = array[row][col].replace(/.*\{row(\d+).*/s, '$1');
for (var r = 1; r < rowspan; r++) array[+row + r].splice(col, 0, '')
}
}
}
return array;
}
It will get you the table like this:
Whrere {row#} and {col#} means how many cells or rows to the left or to the bottom you need to join to the current cell to recreate the original design. It could be the next dose of the intellectual exercises. :)
A solution, example with url = https://www.portaldefinancas.com/js-tx-ctb/th-cdib.js
function getHeaders(url) {
var source = UrlFetchApp.fetch(url).getContentText()
source = source.split('document')[2]
var table = '<table><tr><th ' + source.match(/(?<=<th ).*(?=th>)/g) + 'th></tr></table>'
table=table.replace(/ê/g,'ê').replace(/ú/g,'ú').replace(/<br>/g,'\n')
var doc = XmlService.parse(table);
var rows = doc.getDescendants().filter(function(c) {
var element = c.asElement();
return element && element.getName() == "tr";
});
var n=0
var data=[]
rows.slice(0).map(function(row) {data[n++]=[]})
n=0
rows.slice(0).map(function(row) {
row.getChildren("th").map(function(cell) {
try{nbcols = cell.getAttribute('colspan').getValue()}catch(e){nbcols = 1}
try{nbrows = cell.getAttribute('rowspan').getValue()}catch(e){nbrows = 1}
var value = cell.getValue()
r=0
var free=0
while(r<nbrows*1){
c=0
while(c<nbcols*1){
while(data[n+r][free]!=null){free++}
data[n+r][free]=(value)
value=''
c++
}
r++
}
});
n++
});
return (data);
}

GAS is it possible to replace getActiveDocument().getSelection() at once?

My User has the following selection in his Gdoc.
Now from the sidebar he wants to to replace the selection he made on the document. The GAS question is if it is possible to do that at once, something like:
var selection = DocumentApp.getActiveDocument().getSelection()
selection.replace("newtext")
Or do I have to loop through selection.getRangeElements() in order to delete them (or replace them) and than in someway place the new text in that position?
Not, that's not possible (well, if it is, it's not documented).
You have to loop through the selected elements, mainly because the selection may take part of paragraphs, forcing you to manage that. i.e. deleting just the selected part. And for completed selected elements, you can just remove them entirely (like images).
Here's an implementation on how to do this (part of the Kaylan's Translate script modified by me to properly replace images and partially selected paragraphs.
function replaceSelection(newText) {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
var replace = true;
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
var text = element.getText().substring(startIndex, endIndex + 1);
element.deleteText(startIndex, endIndex);
if( replace ) {
element.insertText(startIndex, newText);
replace = false;
}
} else {
var element = elements[i].getElement();
if( replace && element.editAsText ) {
element.clear().asText().setText(newText);
replace = false;
} else {
if( replace && i === elements.length -1 ) {
var parent = element.getParent();
parent[parent.insertText ? 'insertText' : 'insertParagraph'](parent.getChildIndex(element), newText);
replace = false; //not really necessary since it's the last one
}
element.removeFromParent();
}
}
}
} else
throw "Hey, select something so I can replace!";
}