如何比较电子表格中的两列

时间:2016-08-08 18:29:30

标签: google-sheets google-spreadsheet-api

我有30列和1000行,我想将column1与另一列进行比较。如果价值不匹配,那么我想把它染成红色。下面是我的电子表格中的一个小数据集:

      A       B      C      D   E   F    ...
1    name   sName   email 
2
3
.
n

因为我有一个大型数据集,并且我想将我的列存储在一个数组中,所以第一行是标题。这就是我所做的,但是当测试我得到空的结果时,有人可以纠正我的错误吗?



var index = [];
var sheet = SpreadsheetApp.getActiveSheet();

function col(){
    var data = sheet.getDataRange().getValues();
  for (var i = 1; i <= data.length; i++) {
        te = index[i] = data[1];
        Logger.log(columnIndex[i])
        if (data[3] != data[7]){
            // column_id.setFontColor('red');  <--- I can set the background like this
        }
    }  
}
&#13;
&#13;
&#13;

从代码中你可以看到我正在扫描整个电子表格数据[1]获取标题,并在if循环(data[3] != data[7])中比较两列。我必须处理我的颜色变量,但是一旦我获得了我需要的数据就可以完成。

1 个答案:

答案 0 :(得分:0)

尝试检查此tutorial是否可以帮助您解决问题。本教程使用Google AppsScript来比较两列。如果发现差异,脚本应指出这些差异。如果没有找到任何差异,脚本应该输出文本“[id]”。只需为您自己的功能自定义此代码。

以下是用于实现此类比较的代码

function stringComparison(s1, s2) {
  // lets test both variables are the same object type if not throw an error
  if (Object.prototype.toString.call(s1) !== Object.prototype.toString.call(s2)){
    throw("Both values need to be an array of cells or individual cells")
  }
  // if we are looking at two arrays of cells make sure the sizes match and only one column wide
  if( Object.prototype.toString.call(s1) === '[object Array]' ) {
    if (s1.length != s2.length || s1[0].length > 1 || s2[0].length > 1){
      throw("Arrays of cells need to be same size and 1 column wide");
    }
    // since we are working with an array intialise the return
    var out = [];
    for (r in s1){ // loop over the rows and find differences using diff sub function
      out.push([diff(s1[r][0], s2[r][0])]);
    }
    return out; // return response
  } else { // we are working with two cells so return diff
    return diff(s1, s2)
  }
}

function diff (s1, s2){
  var out = "[ ";
  var notid = false;
  // loop to match each character
  for (var n = 0; n < s1.length; n++){
    if (s1.charAt(n) == s2.charAt(n)){
      out += "–";
    } else {
      out += s2.charAt(n);
      notid = true;
    }
out += " ";
  }
  out += " ]"
  return (notid) ? out :  "[ id. ]"; // if notid(entical) return output or [id.]
}

有关详细信息,请查看上面的教程链接和SO question,了解如何比较两个电子表格。