如何使用GAS填写电子表格中的范围

时间:2014-07-25 21:41:07

标签: google-apps-script spreadsheet

我想知道如何在电子表格中填充和存储多个行和列的范围。我试过了:

   var sheet = ss.getSheets()[0];
   var row  = 1;    // Start at row 1
   var col  = 1;    // Start at column 1
   var rows = Count;    // Number of rows to use
   var cols = 10;   // Number of columns to use
   var range = sheet.getRange(row, col, rows, cols);     

   var arrValues = [];
   var arrRows = [];

   for (var i=0; i<Count; i++)
   {
      arrValues[0] = i;
      ....
      arrValues[9] = 'something';

      arrRows[i] = arrValues;
   }

   range.setValues([arrRows]);

但这不起作用。

我应该如何填写和设置值?

1 个答案:

答案 0 :(得分:1)

这样的事情如何,像你一样在2个循环中构建一个2D数组......

不确定你想用数字索引做什么,所以我把它放在col 1

function fillRange(){
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheets()[0];
  var row  = 1;    // Start at row 1
  var col  = 1;    // Start at column 1
  var Count = 10;
  var rows = Count;    // Number of rows to use
  var cols = 10;   // Number of columns to use
  var dataArray = [];
  for (var i=0; i < rows; i++){
    var rowData = [];
    rowData.push(i);
    for(var c=1 ; c<cols ; c++){
      rowData.push('something');
    }
    dataArray.push(rowData);
  }
  Logger.log(dataArray+' length = '+dataArray.length+'   width = '+dataArray[0].length);
  sheet.getRange(row, col,dataArray.length,dataArray[0].length).setValues(dataArray);
}

如果您需要控制每列中的数据,请使用数组将这些数据存储为常量并更改代码,如下所示:

var someData = ['','value1','other value','another one','again','and','another','data','to be','complete']

function fillRange(){
  var ss = SpreadsheetApp.getActive()
  var sheet = ss.getSheets()[0];
  var row  = 1;    // Start at row 1
  var col  = 1;    // Start at column 1
  var Count = 10;
  var rows = Count;    // Number of rows to use
  var cols = 10;   // Number of columns to use
  var dataArray = [];
  for (var i=0; i < rows; i++){
    var rowData = [];
    rowData.push(i);
    for(var c=1 ; c<cols ; c++){
      rowData.push(someData[c]);
    }
    dataArray.push(rowData);
  }
  Logger.log(dataArray+' length = '+dataArray.length+'   width = '+dataArray[0].length);
  sheet.getRange(row, col,dataArray.length,dataArray[0].length).setValues(dataArray);
}