Format a Google Sheets cell in plaintext via Apps Script

柔情痞子 提交于 2019-11-27 15:27:22

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

A complement to Christian good answer : I have noticed that if your target cell has already been set to text format (manually), setting a value with range.setValue() that might not been interpreted as a text (like a date, or a number), will change automatically the number format. So the good solution, if you want definitely to keep a text format is

range.setValue("01293849847").numberFormat("@");

and not

range.numberFormat("@").setValue("01293849847");

Unfortunately the text of the plan did not fit. Document as soon as the cell gets something like a date, just format the cell. Found a way not to create date)

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

Sorry so late reply. All hands did not reach.

Another way to force the value to be saved as plain text:

Prepend a quotation mark: '. This has no effect on displayed value and also by reading the value back the quatation mark is not included.

let dateStr = '07-07-20017';
sheet.getRange(x, y).setValue("'" + dateStr);

let backStr = sheet.getRange(x, y).getValue();
assert(dateStr === backStr);

I did it like below and it works as I expected. My B column show correct zero filled 3 digit number (e.g., 004) and my C column shows correct zero filled 10 digit number (e.g., 0060000001) as texts. I downloaded the file it converted to Excel as texts with the padded zeros. I think it would do the trick with the Date as a text as well.

winSS.getRange("US!B2:B").setNumberFormat("000").setNumberFormat("@"); winSS.getRange("US!C2:C").setNumberFormat("0000000000").setNumberFormat("@");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!