google-apps-scriptgoogle-drive-apigoogle-sheets-apibatch-request

how to remove empty rows and columns using batch request


I have a code by which I remove all empty rows and columns from a sheet. Is it possible to use a batch request to speed up the script's work, because when there are a lot of files, it takes a very long time?

Code below

    while ( files.hasNext()){
   var file1 = files.next().getId();
 var sheet = SpreadsheetApp.openById(file1);
var allsheets = sheet.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxColumns = sheet.getMaxColumns(); 
var lastColumn = sheet.getLastColumn();
var maxRows = sheet.getMaxRows(); 
var lastRow = sheet.getLastRow();
if (maxRows-lastRow === 0){}
else {
if (maxRows-lastRow != 0){
      sheet.deleteRows(lastRow+1, maxRows-lastRow);
      }
      console.log(sheet)
if (maxColumns-lastColumn != 0){
      sheet.deleteColumns(lastColumn+1, maxColumns-lastColumn);
      }
      console.log(sheet)
    }
  }
 }

I would be grateful for any help


Solution

  • I believe your goal as follows.

    Modification points:

    When above points are reflected to your script, it becomes as follows.

    Modified script:

    Before you use this script, please enable Sheets API at Advanced Google services.

    while (files.hasNext()){
      var file1 = files.next().getId();
      var ss = SpreadsheetApp.openById(file1);
      var sheets = ss.getSheets();
      var requests = sheets.reduce((ar, sheet) => {
        var sheetId = sheet.getSheetId();
        var maxColumns = sheet.getMaxColumns(); 
        var lastColumn = sheet.getLastColumn();
        var maxRows = sheet.getMaxRows(); 
        var lastRow = sheet.getLastRow();
        if (lastRow > 1 && maxRows > lastRow) {
          ar.push({deleteDimension: {range: {sheetId: sheetId, dimension: "ROWS", startIndex: lastRow}}});
        }
        if (lastColumn > 1 && maxColumns > lastColumn) {
          ar.push({deleteDimension: {range: {sheetId: sheetId, dimension: "COLUMNS", startIndex: lastColumn}}});
        }
        
        // For empty sheet, when you want to leave only cell "A1", please use the following script.
        // if (lastRow == 0 && lastColumn == 0 && maxRows > 1 && maxColumns > 1) {
        //   ar.push({deleteDimension: {range: {sheetId: sheetId, dimension: "ROWS", startIndex: 1}}});
        //   ar.push({deleteDimension: {range: {sheetId: sheetId, dimension: "COLUMNS", startIndex: 1}}});
        // }
    
        return ar;
      }, []);
      if (requests.length > 0) {
        Sheets.Spreadsheets.batchUpdate({requests: requests}, id);
      }
    }
    

    Note:

    References: