3

Following sample code gets interpreted as Date formatted cell which is not my intent. It is supposed to be plain text. Calling clearFormat() on the Range is unhelpful either.

function myFunction() {
  SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue("11-2");
}
shoban
  • 650
  • 1
  • 9
  • 14

2 Answers2

4

Based from this blog, you can set the formatting of a single cell, a whole column starting from a specific cell or an entire spreadsheet. You can find additional resources on the Google Sheet support page for number formats.

// Use these first two lines for all four examples
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// Single cell
var cell = sheet.getRange("B2");

// Plain text
cell.setNumberFormat("@");

Also from this google forum, you can use range.setNumberFormat('@STRING@'); to format cells to plain text.

Check these links:

The other answer, to set the format to 'plain text' in javascript, doesn't work. However, this does:

sheet.getRange(1,n).setNumberFormat('@STRING@');

So the magic value for formatting text programmatically is '@STRING@'!

Hope this helps!

Community
  • 1
  • 1
abielita
  • 13,147
  • 2
  • 17
  • 59
  • This snippet saved me a lot of time ```range.setNumberFormat('@STRING@');```. Thank you my friend. – TroniPM Jun 11 '23 at 21:59
0

It looks like a number when the spreadsheet parser encounters it first so it is stored as a number inside it's system.

A standard way of forcing the parser to accept anything as being text is to pre-pend the input with an apostrophe '

So your script becomes:

function myFunction() {
   SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue("'11-2"); 
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
David Tew
  • 1,441
  • 1
  • 10
  • 12