Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...