在我的Google Apps脚本中,我在电子表格中添加了一行。在这一行被追加,我试图插入一个值为' 0102'的字符串,但是当插入它时会转换为数字102.有没有办法将值插入到使用Google Apps脚本的工作表中不要将这些类型的数字格式化为整数,而是将它们保留为字符串?
答案 0 :(得分:3)
You need to format the cell as plain text before setting its value. From this answer, the (seemingly undocumented) trick is setNumberFormat('@STRING@')
. For example,
sheet.getRange("A1").setNumberFormat('@STRING@').setValue('0102');
formats cell A1 as plain text, and sets the value '0102', which will remain a string.
Unfortunately, appendRow
, being an atomic operation of adding a row and inserting values, does not leave room for formatting. So you'll need something more verbose, for example
sheet.insertRowAfter(sheet.getLastRow());
var range = sheet.getRange(sheet.getLastRow() + 1, 1, 1, 3);
range.setNumberFormats([['', '', '@STRING@']]).setValues([['Boston', 'MA', '02201']]);
This code adds a row and fills the first three cells in it with Boston MA 02201, keeping the ZIP code 02201 as a string.
答案 1 :(得分:0)
以为我会在我自己的解决方案中添加我遇到的同样问题。
我发现的修复是,如果你在前面添加一个'
字符,你试图插入的值会强制它保留为字符串。
sheet.appendRow(["Boston", "MA", "'02201"])