Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a Google Sheets cell in plaintext via Apps Script

Using Google Apps Script, I want to set the format for a Google Sheets cell to plain text.

The reason I want to do this is because I want to show a date in the U.S. date format (MM/DD/YYYY). [We can assume the locale in the OP's Google account is set to use DD/MM/YYYY, a more common date format. –Ed.]

I create the string like this:

var thisDate = Utilities.formatDate (new Date (), SpreadsheetApp.getActiveSpreadsheet (). getSpreadsheetTimeZone (), "MM / d / yyyy"); 

... which returns the date in the U.S. format, 06/13/2012, which is what I want. However, when I set the value of a cell to that string:

sheet.getRange (1, n). setValue (thisDate); 

... the date is formatted into the cell according to my locale, 13/06/2012, not the U.S. format.

The following operation also fails, because the date is returned in the standard format, not the U.S. format:

sheet.getRange (1, n). getValue () == "06/13/2012" 

When the cell is formatted as plain text, and not a date, everything works fine.

So, my question is, how to format a cell using JavaScript.

like image 720
Anton Pil Avatar asked Dec 07 '12 07:12

Anton Pil


People also ask

How do you change to plain text in Google Sheets?

Plain text format In such a scenario, we may have to manually force Google Sheets to treat the string of numbers as text, which otherwise would have been treated as an actual number. So, in the cell A6, if it is supposed to be a text value, we can do that. Select cell A6. Now navigate to Format > Number > Plain text.


1 Answers

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@'!

like image 194
christian.simms Avatar answered Oct 04 '22 11:10

christian.simms