Google Apps Script 设定Spreadsheet Cell为纯文字格式

前言

读此篇文章时必需要俱备Google Apps Script的开发基础,其文章主要会以快速记录开发心得所提供的程式内容技巧,有不能理解之处请下留言处留言。

问题

使用setValue输入数字,但显示出来的数字被格式化成非预想的结果

123456->12,345

技巧

使用getRange()之后会将取到的资料范围进行资料修改,SpreadSheet会根据你输入的资料内容进行判断它的资料格式,当你输入为12345时会被判为数字,因而会被被格式化成像这样12,345,所以除了重设定格式之外,也可以将它设定为纯文字就不会有这问题:

    var sheet = SpreadsheetApp.openById(spreadsheetID).getSheets()[sheetIndex];
    var dataRange = sheet.getRange("A2");
    dataRange.setNumberFormat("@");
    dataRange.setValue(value);


官方网页上有篇Date and Number Formats 提供设定格式的说明,但标题的关系会以为只教你设定日期与数字,但Number format tokens表格有说明设定为raw text的方法:

Token Description
@ Inserts the raw text for the cell, if the cell has text input. Not compatible with any of the other special characters and won’t display for numeric values (which are displayed as general format).