【问题标题】:What's the function to get a value of a cell?获取单元格值的函数是什么?
【发布时间】:2022-12-03 08:37:21
【问题描述】:

一开始我以为函数是

spreadsheet.getValue('A1')

但这似乎不起作用。是否可以执行具有类似功能的循环或操作?如果没有,我如何将值存储在变量中?

我知道这是一个非常基本的问题,但我在文档中找不到任何内容。我对这种语言真的很陌生。

【问题讨论】:

  • 有关官方文档、免费资源和更多详细信息,请参阅tag info page。

标签: google-apps-script google-sheets


【解决方案1】:

要获取A1的值,需要先使用getRange()。

console.info(
  SpreadsheetApp.getActive() // Returns class Spreadsheet
   .getSheetByName('Sheet1') // Returns class Sheet
   .getRange('A1')  // Returns class Range
   .getValue() // Returns type string or number or date according to the cell's type
)

【讨论】:

【解决方案2】:

有几种方法可以从 Google 表格中获取单元格值。首先,您应该知道 Google Apps 脚本使用 JavaScript 作为编程语言。 Google Apps 脚本具有电子表格服务。该服务包括多个类、枚举和方法,可以轻松处理 Google 表格电子表格。

下面有 5 个示例显示了一些获取单元格值的方法。前 4 个示例使用 Range 对象,第 5 个示例不使用 Range 对象。

/**
 * Get a value using A1 (cell using A1 notation) style reference from the first sheet
 */
function sample1(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const range = spreadsheet.getRange('A1');
  const value = range.getValue();
  console.log(value);
}
/**
 * Get a value using Sheet1!A1 (sheet name and cell using A1 notation) style reference
 */
function sample2(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const range = spreadsheet.getRange('Sheet2!A1');
  const value = range.getValue();
  console.log(value);
}
/**
 * Get a value using Sheet1!R1C1 (sheet name and cell using R1C1 notation) style reference
 */
function sample3(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const range = spreadsheet.getRange('Sheet2!R1C1');
  const value = range.getValue();
  console.log(value);
}
/**
 * Get a value by using a Sheet and Range objects.  
 * This sample uses Spreadsheet.getSheetByName to get a Sheet object.
 */
function sample4(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadsheet.getSheetByName('Sheet2');
  const range = sheet.getRange('A1');
  const value = range.getValue();
  console.log(value);
}

注意:除了使用 A1 和 R1C1 符号外,对于 getRange,还可以使用 getRange(1,1)(第一个参数是行,第二个是列,使用基于 1 的索引)

/**
 * Get a cell value from the first sheet by using JavaScript Arrays
 * The parameters of getSheetValues are start row, start column, 
 * number of rows, and number of columns
 * Please bear in mind that getSheetValues uses 1 for the first row and 
 * column but JavaScript Arrays use 0 for the first Array member
 */
function sample5(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const values = spreadsheet.getSheetValues(1,1,1,1); 
  const value = values[0][0];
  console.log(value);
}

资源

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多