简体   繁体   中英

Iterating over a number of spread sheets in a folder and I want to pull last 3 columns from each

I am trying to find a solution to pull the data of a number of sheets into a single master doc. I am only interested in the last three columns of each sheet, however the sheets do not all have the same number of columns.

    function getDataFromSpreadsheet(ssID) {

  var ss = SpreadsheetApp.openById(ssID);
  var ws = ss.getSheets()[0];
  var data = ws.getRange("A1:W" + ws.getLastRow()).getValues();
return data;

}

I assume I can do something with getrow.length()[-3] but I am having no luck at all getting it to work.

Change your range

from:

var data = ws.getRange("A1:W" + ws.getLastRow()).getValues();

to:

var data = ws.getRange(1, ws.getLastColumn()-2, ws.getLastRow(), 3).getValues();

Example:

Sheet1:

在此处输入图像描述

Output:

在此处输入图像描述

References:

  function get_last_three_columns_from_spreadsheet_and_sheet(
     spreadsheet_id = SpreadsheetApp.getActiveSpreadsheet().getId(),
     sheet_name = SpreadsheetApp.getActiveSheet().getName()
   ) {
     const spreadsheet = SpreadsheetApp.openById(spreadsheet_id);
     const sheet = spreadsheet.getSheetByName(sheet_name);
     const last_column = sheet.getLastColumn();
     const last_three_columns = [last_column, last_column - 1, last_column - 2];
   
     const data = last_three_columns.map((column) => {
       const last_row = sheet.getLastRow();
       return sheet.getRange(1, column, last_row).getValues();
     }, sheet);
     
     Logger.log(data);
     return data;
   }

Posted on Reddit too, I'd try something like this. You can slap the function right into any spreadsheet script and run it.

By default, if you give it no arguments it'll use just the active spreadsheet and sheet.

If you call it from somewhere else, if you give it a spreadsheet and sheet name argument it'll get the last three columns of info if they're available. It'll error if you have a sheet with less than three columns.

The constant "last_three_columns" can be edited to get the last 4 or 5 or n by just adding another "last_column - n" to the array.

If you want the function to work for some specified n of columns, it would need some adjustments but the original scope was for the last 3 of columns.

The result is an array of 2D Column arrays like,

// Output
[
  [["Column 3"], ["data"], etc.],
  [["Column 2"], ["data"], etc.],
  [["Column 1"], ["data"], etc.]
]

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