Reputation: 49
I have a google sheet that has formatted text in a cell. Some of the text has color and is bold. I use a google script to add new content in the cell. When I run the script, the new content is added but the formatting of the old content is removed.
1) How can I keep the formatting of the old content when executing my script. 2) I want to make the new content bold and colored. How can I format the newcontent that is added to the cell?
Here is the content of my cell before executing the script
Here is my script:
function CreateIssue() {
var spreadsheet = SpreadsheetApp.getActive();
var cell = spreadsheet.getCurrentCell();
var oldContent = cell.getValue();
var newContent ='Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest
Results:\n\nTest Data:';
var space = " ";
cell.setValue(newContent + space + oldContent);
Here is the content of my cell after executing the script
As you can see, the formatting was cleared for the old content.
Upvotes: 1
Views: 4835
Reputation: 201643
If my understanding is correct, how about this answer? Please think of this as justo one of several possible answers.
When the value is put using setValue
, it seems that the text style is cleared. This might be the specification. So in this case, in order to set the text style, I used Class TextStyleBuilder and Class RichTextValueBuilder. The flow of this modified script is as follows.
newContent
and space
.oldContent
.When your script is modified, it becomes as follows. Please select a cell including oldContent
and run the script. By this, newContent
and space
are added to oldContent
, and the text styles are set.
function CreateIssue() {
var spreadsheet = SpreadsheetApp.getActive();
var cell = spreadsheet.getCurrentCell();
var oldContent = cell.getValue();
var newContent = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:';
var space = " ";
// I added below script.
var newStyles = [{
start: 0,
end: newContent.length,
style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("green").build()
}];
var richTextValue = cell.getRichTextValue();
var offset = newContent.length + space.length;
var oldContent = richTextValue.getText();
if (oldContent.length > 0) {
richTextValue.getRuns().forEach(function(e) {
newStyles.push({
start: offset + e.getStartIndex(),
end: offset + e.getEndIndex(),
style: e.getTextStyle()
});
});
}
var richText = SpreadsheetApp.newRichTextValue().setText(newContent + space + oldContent);
newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
cell.setRichTextValue(richText.build());
}
When var newContent = "foo";
is set and select a cell including the text of "bar" which has the text style and run the above script, the following result can be obtained.
The original text style is kept and the additional text has the text style.
If I misunderstood your question and this was not the direction you want, I apologize.
Upvotes: 8