I am working with a script that translates a text in a cell of a sheet through the Deepl API.
Thanks to a colleague help it worked correctly (Use Deepl API and google sheets).
In this case, I need to know how I can make the result of the translation to be included in a cell of the same sheet.
My data object is the following. The first script picks up the text from column 2, row 3. It would be perfect if the result is printed in column 2, row 4, but I don't know exactly how to do it.
I include an image of the corresponding data
I am using this script to translate the text of a cell in my sheet:
function deeplapi() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var text = sheet.getRange(3,2).getValue(); // define text before response
var response = UrlFetchApp.fetch("https://api.deepl.com/v2/translate?auth_key=xxxx-xxxx-xxxx-xxxx-xxxx&text="+ text +"&target_lang=en&source_lang=es");
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
This way I get the result in the records section, but with this format:
Información {translations=[{text=Hi, I'm Carlos, detected_source_language=ES}]}
First, I have tried to extract only the translation in this section and then add it in the same sheet. With this I get the exact translation, but I don't know how to include it in a specific range of my sheet.
Logger.log(data.translations[0].text);
In addition to this, I think that to get this result and paste it in the sheet I would have to use:
sheet.getRange () .setValues (sortedOutput);
Anyway, I'm not sure
Try something like that at the bottom of your script to paste the translation text into cell B4:
sheet.getRange('B4').setValue(data.translations[0].text)
Minimal reproducible example:
const data = {translations:[{text:"Hi, I'm Carlos", detected_source_language:"ES"}]};
console.log(data.translations[0].text)
Related
I've got a Google App Script which is copying rows from one sheet to another, performing various transformations. This logic ultimately gets rows onto the new sheet using sheet.appendRow(row detail). I would like these newly created rows to have a background colour (my intention is to hold a 'latestColour' so I can alternate the shading).
So, is there anyway to add shading within the appendRow method itself, or easily determine the range that the appendRow method processed, such that I can apply additional logic to add the shading.
You can use conditional formatting
=and(A1<>"",A2="")
Although I'm not sure whether I could correctly understand your situation, from your question, I thought that you might be using [Format] --> [Alternating colors] in Google Spreadsheet. And, when a new row is appended by putting the values, you might want to reflect "Alternating colors" in the appended row. If my guess is correct, how about the following sample script?
Sample script:
function myFunction() {
const addValues = ["sample1", "sample2", "sample3"]; // This is a sample appending value. Please replace this for your value.
const sheetName = "Sheet1"; // Please set the sheet name.
// Retrieve banding object from the data range.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const b = sheet.getDataRange().getBandings();
if (b.length == 0) {
console.log("Bandings are not used.");
return;
}
// Append the value.
sheet.appendRow(addValues);
// Expand the range of banding.
b[0].setRange(sheet.getDataRange());
}
When this script is run, the current banding is retrieved. And, after the value was appended, the banding is updated by including the appended row. In this sample, even when the multiple rows are appended, this script can be used.
Note:
From your question, I guessed that there is one banding in the data range in your sheet. Please be careful this.
References:
getBandings()
setRange(range)
Unfortunately the method appendRow() does not receive formatting settings as input, only an array of values.
However, here is a suggestion if you want to implement your own logic:
Sample code:
function applyColorLastRow() {
var ss = SpreadsheetApp.getActive(); //get active sheets file
var range = ss.getDataRange(); //get populated range, you may want to set a range manually if needed.
var lastRowNum = range.getLastRow(); //getting the last row index of the range.
var lastRowRange = ss.getRange(`${lastRowNum}:${lastRowNum}`); //narrowing the range (using A1 notation) to the last row only to apply color
var lastRowColor = lastRowRange.getCell(1,1).getBackgroundObject().asRgbColor().asHexString();
//Your row coloring logic here...
if (lastRowColor === '#ffffff'){ //toggling white/grey color as an example...
lastRowRange.setBackground('#cccccc'); //apply grey color to all cells in the last row range
} else {
lastRowRange.setBackground('#ffffff'); //apply white color to all cells in the last row range
};
}
I'm dealing with an annoying problem when importing data into Google Spreasheets using Google App Script
Basically the code is as follows:
var csvData = Utilities.parseCsv(mySource,separator);
range.setValues(csvData);
usually this works perfectly but sometimes we have a productcode column which gets messed up
productcode
value
01DECUB003
100
21MAR003
200
The second row gets messed up because the product code is interpreted as a Date and thus converted into 21mar2003 which in turn does not match any of the real product code and then raises errors in further export scritps.
Is there any way to fix this? I don't see any relevant option neither within Utilities nor within Range.
Is there any alternative APIs for doing the same?
Here's an example which reproduces the issue
create a new sheet and name the first (and only) tab "IMPORT"
set the "sheet settings" locale to "Italian"
create and run the following script
function main() {
var csvContent= 'code;value\n01mmabc001;111,1\n21mar003;222,2';
var separator= ';';
var csvData = Utilities.parseCsv(csvContent,separator);
var sheet = SpreadsheetApp.getActiveSheet();
var range;
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("IMPORT");
range = sheet.getRange(1, 1, csvData.length, csvData[0].length);
range.setValues(csvData);
}
I have been able to do it by changing this:
range = sheet.getRange(1, 1, csvData.length, csvData[0].length);
to this:
range = sheet.getRange(1, 1, csvData.length, csvData[0].length).setNumberFormat('#');
What this does is while getting the range it sets the format of the cells to #:
Inserts the raw text for the cell, if the cell has text input. Not compatible with any of the other special characters and won’t display for numeric values (which are displayed as general format).
Reference:
setNumberFormat(numberFormat)
Number format tokens
"Insert Link" is not producing a =HYPERLINK(’’,’’) anymore.
Before, if you linked a cell with a value ‘X’. It was converted into the formula =HYPERLINK(*link*,’X’)
Two days ago "Insert Link" changed.
Now the content of the cell remains the same, it is just underlined.
Using a script, how can I extract the link from a Cell now that neither its value nor its formula contains this information?
I searched the documentation but the only method related to links that I was able to find was setShowHyperlink(showHyperlink)
I could confirm your situation. In this case, it seems that the hyperlink can be retrieved from RichTextValue object. Namely, I thought that the specification was changed to that the hyperlink is given to the text using RichTextValue.
So as a sample case, it supposes as follows.
A text of X is put in a cell "A1".
This cell is manually linked to a URL like https://www.google.com.
In this case, the cell has no =HYPERLINK("https://www.google.com","X"). The sample script for retrieving the URL from this situation is as follows.
Sample script:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var url = sheet.getRange("A1").getRichTextValue().getLinkUrl();
console.log(url);
In this case, the URL is linked to whole text in a URL. So above script can be used.
Note:
In the current stage, the multiple hyperlinks can be added to the texts in one cell. For example, when 2 URLs are put to the text in a cell, you can use the following sample script. In this sample, a text of url1, url2 is put to a cell "A1", and url1 and url2 are linked with each link.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var RichTextValue = SpreadsheetApp.newRichTextValue()
.setText("url1, url2")
.setLinkUrl(0, 4, "https://url1/")
.setLinkUrl(6, 10, "https://url2/")
.build();
sheet.getRange("A1").setRichTextValue(RichTextValue);
When the multiple URLs are retrieved from the text in a cell, you can use the following sample script.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange("A1");
var RichTextValue = range.getRichTextValue().getRuns();
var res = RichTextValue.reduce((ar, e) => {
var url = e.getLinkUrl();
if (url) ar.push(url);
return ar;
}, []);
console.log(res);
References:
getRichTextValue()
getRichTextValues()
Class RichTextValue
Updated at June 13, 2020:
By the update at June 12, 2020, the documents of getLinkUrl() and setLinkUrl(linkUrl) were added to the official documents.
I need a way to transfer the data from a google document to be transferred over to a google spreadsheet (kind of backwards, I know). I need the line breaks in the document to be equivalent to starting a new cell right below. i.e. each line in the google doc has its own cell.
I've tried getting the body text from the google doc and setting the first cell as that variable but that only pastes the data in the single A1 cell (kind of want it to be similar to the way if you copy and paste doc body text into the A1 cell it will populate cells in the A column all the way down)
var body = openedFile.getBody().getText();
var newSpreadsheet = SpreadsheetApp.create('TEST').getId();
var testSpreadsheet = SpreadsheetApp.openById(newSpreadsheet);
testSpreadsheet.getRange('A1').setValue(bodyAll);
You want to put each paragraph of Document to the cells of Spreadsheet which was created in the script.
From your script, your Google Document has only texts. Your Google Document doesn't include tables, lists, images and so on.
If my understanding is correct, how about this modification?
Pattern 1:
In this pattern, body of var body = openedFile.getBody().getText() is splitted by \n. Then, the values are put to the created Spreadsheet.
Modifed script:
var openedFile = DocumentApp.openById("###"); // Please set Document ID here.
var body = openedFile.getBody().getText();
var bodyAll = body.split("\n").reduce(function(ar, e) {
if (e) ar.push([e]); // If you want to include the empty paragraph, please modify to ar.push([e]);
return ar;
}, []);
var newSpreadsheet = SpreadsheetApp.create('TEST');
newSpreadsheet.getSheets()[0].getRange(1, 1, bodyAll.length, bodyAll[0].length).setValues(bodyAll);
Pattern 2:
In this pattern, the paragraphs are retrieved from the body of Document, and each text is retrieved. Then, the values are put to the created Spreadsheet.
Modifed script:
var openedFile = DocumentApp.openById("###"); // Please set Document ID here.
var body = openedFile.getBody();
var bodyAll = body.getParagraphs().reduce(function(ar, e) {
var temp = e.getText();
if (temp) ar.push([temp]); // If you want to include the empty paragraph, please modify to ar.push([temp]);
return ar;
}, [])
var newSpreadsheet = SpreadsheetApp.create('TEST');
newSpreadsheet.getSheets()[0].getRange(1, 1, bodyAll.length, bodyAll[0].length).setValues(bodyAll);
Note:
In this script, the empty paragraphs are ignored. If you want to include the empty paragraphs, please modify the script like the comment.
References:
split()
getParagraphs()
reduce()
If above scripts didn't resolve your issue, I apologize. At that time, in order to correctly understanding your situation, can you provide a sample Document and a sample Spreadsheet of the result you want? Of course, please remove your personal information from them.
I have a form and an API a Google Apps Script attached to it.
After sending the form I want to confirm that the script ran successfully with no errors by adding a value V to the last column of the form response's spreadsheet.
But I can't find any way to edit an existing row. Can someone help me with that?
Additional information from comments:
var responsesSSID = SpreadsheetApp.openById('*****************');
var values = responsesSSID.getDataRange().getValues();
values[values.length-1][values[].length-1] = "V";
I couldn't find anything here (for the next line) that will work.
Assuming that you want to update/edit the last column of the last row of your spreadsheet :
var sprdkey = '0Ai4sb45QfOAQdGhRWEtQaTR0enVHUHlxSTlobkVtenc';
var sheet = SpreadsheetApp.openById(sprdkey).getActiveSheet();
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
sheet.getRange(lastRow , lastCol).setValue("V");
If you need to edit any other cell in the spreadsheet, you just need to pass the appropriate parameters to the getRange(row_no, col_no) function.
Hope this helps!