按列名称而不是列索引获取列值 [英] Get column values by column name not column index

查看:106
本文介绍了按列名称而不是列索引获取列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉Google Apps脚本。我想通过它的列名来获取特定单元格的值,而不是列索引。这是我的:

  var rows = sheet.getDataRange(); 
var values = rows.getValues();
var row = values [1];
var rowStaffName = row [0];

不是使用 row [0] ,我想使用列名称。有没有一种简单的方法来做到这一点?

解决方案

以下函数重试列中给定名称的值,给定行。

  function getByName(colName,row){
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange()。getValues();
var col = data [0] .indexOf(colName);
if(col!= -1){
return data [row-1] [col];




$ b特别是 var col = data [0] .indexOf(colName); 在工作表的首行查找给定名称。如果找到,则返回该列给定行中的值( row-1 用于说明基于0的JavaScript索引)。

为了测试它的效果,请尝试类似于

 函数测试(){
Logger.log(getByName('Price',4)); //或者任何你想要的名字或行

code $ pre

I'm new to Google Apps Script. I want to get the value of a specific cell by it's column name, not the column index. Here is what I have:

var rows = sheet.getDataRange();
var values = rows.getValues();
var row =values[1];
var rowStaffName = row[0];

Instead of using row[0], I want to use the column name. Is there an easy way to do that?

解决方案

The following function retries the value in a column with a given name, in a given row.

function getByName(colName, row) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var col = data[0].indexOf(colName);
  if (col != -1) {
    return data[row-1][col];
  }
}

Specifically, var col = data[0].indexOf(colName); looks up the given name in the top row of the sheet. If it's found, then the value in the given row of that column is returned (row-1 is used to account for JavaScript indices being 0-based).

To test that this works, try something like

function test() {
  Logger.log(getByName('Price', 4)); // Or whatever name or row you want
} 

这篇关于按列名称而不是列索引获取列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆