在Google App Script中存储数组并将数组打印到Google表格列

时间:2016-10-23 22:21:53

标签: javascript arrays google-apps-script google-sheets

我正在处理Google表格,我试图在数组中存储一列整数,然后清除工作表上的一列,然后将整数数组打印到工作表上的一列。请参阅下面的代码......

function myFunction1() {

//Declaring the Active Sheet
var mySheet = SpreadsheetApp.getActiveSheet();

//Declaring the range that will make up the Array
var myRange = mySheet.getRange("E10:E328");

//Declaring Array 
var myArray = [[myRange.getValues()]];

//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();

//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues([myArray]);

}

上面的代码运行没有任何错误,但不会将我的数组打印到工作表。我已经在这方面工作了一段时间,并使用以下文章来尝试修复它......

https://productforums.google.com/forum/#!topic/docs/t99laH0rFc0

Incorrect Range Height - Google Script

Writing 1D array into a sheet column in Apps Script

https://developers.google.com/apps-script/reference/spreadsheet/range#setvaluesvalues

到目前为止编写代码时遇到的常见错误是"不正确的范围高度"和"无法将数组转换为对象[] []"。

我如何解决这个问题,以便我的数组打印到工作表上的列?

感谢您的时间!任何有关这方面的帮助都会很棒!!

3 个答案:

答案 0 :(得分:1)

你做得比你要复杂得多。

function myFunction1() {

//Declaring the Active Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();  
var mySheet = ss.getActiveSheet();

//Declaring the range that will make up the Array
var myArray = mySheet.getRange("E10:E328").getValues();//already in an array

//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();

//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues(myArray); //already in an array don't need brackets

}

答案 1 :(得分:0)

很难确切地说出你想要做什么。但是,如果您尝试将列A替换为E列,请执行以下操作:

function myFunction1() {
var mySheet = SpreadsheetApp.getActiveSheet();
var myRange = mySheet.getRange("E10:E328").getValues();
mySheet.getRange('A10:A328').setValues(myRange);
}

答案 2 :(得分:0)

// Write data in cell G1, H1, I1

function arrayPlay() {
  
  var newArray = [];

  // Variable that saves the data from G1->I1.
  var cellIn1 = ("G1");
  var cellIn2 = ("H1");
  var cellIn3 = ("I1");
  
  var sheet = SpreadsheetApp.getActiveSheet();
  
  // Defines where the data is recieved. (G1, H1, I1)
  var cellOut1 = sheet.getRange(cellIn1);
  var cellOut2 = sheet.getRange(cellIn2);
  var cellOut3 = sheet.getRange(cellIn3);
  
  // Recieve the data from those cells
  var data1 = cellOut1.getValue();
  var data2 = cellOut2.getValue();
  var data3 = cellOut3.getValue();
  
  // Puts the data in the Array. (newArray)
  newArray.push(data1, data2, data3)
    
  // Presents the data in Cell 1-3 (A1, A2, A3)) Downwards
   sheet.appendRow([newArray[0]]);
   sheet.appendRow([newArray[1]]);
   sheet.appendRow([newArray[2]]);
  
  // Presents the data in Cell 1-3 (A1, B1, C1) Sideways
  sheet.appendRow([newArray[0], newArray[1], newArray[2]]);

  Logger.log(newArray);
  
}