简体   繁体   中英

“TypeError: Cannot read property 'length' of undefined” Converting Google Sheet data into a Google Doc template using Google Apps Script

Google sheet folder containing files: https://drive.google.com/drive/folders/1hPKQk7eRjSdlMDjiZI2BZrHIRhzVtYG5?usp=sharing

Im trying to fill out templates in google docs using data from my Test Merge google sheet file, specifically in the tab named "PrintThis". I have a Google Apps script added to my "Test Merge" google sheet file but im getting this error: "TypeError: Cannot read property 'length' of undefined". The data in PrintThis will be varying in the number of rows so I am guessing the error is caused by this line?

    var tactics = Sheets.Spreadsheets.Values.get('1xSWskGS8B_3Y35I4ycAjFZQiGbfJo13O3837RKnxnpk', 'A4:J');    

But when I do A4:J6 just to test it for this static set of data it still gives me the same error. How do I fix this in a way that even when the PrintThis tab has a dynamic number of rows and my PrintThis tab can be moved(ex. a new sheet/tab can be placed on the left or right of the PrintThis tab)?

If you want to get the value of "Test Merge" using Sheets API, make sure to add the sheet name along with the range. Example: "Test Merge:A4:J"

Example:

测试数据

Code:

function myFunction() {

  Logger.log(Sheets.Spreadsheets.Values.get('somespreadsheetid', 'Test Merge!A4:J').values);
}

Output:

测试数据1

Or

Since you are using Google Apps Script, you could use SpreadsheetApp .

Code:

function myFunction() {
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test Merge");
  var range = sh.getRange(4, 1, sh.getLastRow() - 4 + 1, 10);
  var val = range.getValues();
  Logger.log(val)
}

Output:

在此处输入图像描述

References:

SpreadsheetApp

Method: spreadsheets.values.get

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM