删除Google电子表格中的所有空行

时间:2014-10-15 15:36:12

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

我刚刚开始使用Google Apps脚本管理我正在处理的项目的一些工作表,我是Javascript的新手,所以如果我的代码中有任何咆哮,请放心!

我们已经和应用程序调用了forms2mobile,它可以捕获数据并将其放入Google电子表格中。它实际上将不同的数据放入不同的表格中,具体取决于您使用的应用程序的哪个部分。

我一起攻击了一个脚本,该脚本从一个工作表(源)中提取所有数据,并且只将某些列放入第二个工作表(目标)。然后删除源中的所有行以及目标中的所有空行。

我遇到的问题是从目标中删除空白行。通常,目标在底部会有空行,而我所拥有的代码只会删除包含数据的范围内的空行。所以我总是在底部留下空行。

然后,目标表将用作forms2mobile的数据源,当然对空行不满意。

我发现了类getMaxRows(),但我不确定如何实现它。如果有人能提出任何好的建议。

干杯 保罗

    function NEW_copyColumnNumbers( ) {
    var spreadsheet_source = SpreadsheetApp.openById('1a89ZIUcy-8168D1damCV3Q9Ix0arQn9jGS6pgp');
    var spreadsheet_target = SpreadsheetApp.openById('1GQiLt9utSH_6CV__oJwmcLOkI4E9iNIRPWU7Xr');
    var range_input = spreadsheet_source.getRange("A2:CC407");
    var range_output = spreadsheet_target.getRange("A"+(spreadsheet_target.getLastRow()+1));
    var keep_columns = [66,66,10,11,12,13,14,23,26,31,69,71,74,75,80];

    copyColumnNumbers(range_input, range_output, keep_columns);
    clearEmptyRows();
    clearSourceData();
}
function copyColumnNumbers( range_input, range_output, columns_keep_num ) {
    // Create an array of arrays containing the values in the input range.
    var range_values = range_input.getValues();    
    // Loop through each inner array.
    for ( var i = 0, row_count = range_values.length;  i < row_count; i++ ) {
        // Loop through the indices to keep and use these indices to 
       // select values from the inner array.
        for ( j = 0, col_keep_count = columns_keep_num.length; j < col_keep_count; j++ ) {
              // Capture the value to keep
              var keep_val = range_values[i][columns_keep_num[j]];
              // Write the value to the output using the offset method of the output range argument.
              range_output.offset(i,j).setValue(keep_val);
        }
    }
}
function clearEmptyRows() {
  var ss = SpreadsheetApp.openById('1GQiLt9utSH_6CV__oJwmcLOkI4E9iNIRPWU7Xr');
  var s = ss.getActiveSheet();
  var values = s.getDataRange().getValues();
  nextLine: for( var i = values.length-1; i >=0; i-- ) {
    for( var j = 0; j < values[i].length; j++ )
      if( values[i][j] != "" )
        continue nextLine;
    s.deleteRow(i+1);
  }
  //I iterate it backwards on purpose, so I do not have to calculate the indexes after a removal
}
function clearSourceData() {
  var ss = SpreadsheetApp.openById('1a89ZIUcy-8168D1damCV3Q9Ix0arQn9jGS6pgp');
  var s = ss.getActiveSheet();
  var data = s.getDataRange().getValues();
  for(var n =data.length+1 ; n<0 ;  n--){
    if(data[n][0]!=''){n++;break}
  }
  s.deleteRows(2, (s.getLastRow()-1));
}

7 个答案:

答案 0 :(得分:9)

这是它的工作原理:

function removeEmptyRows(){
  var sh = SpreadsheetApp.getActiveSheet();
  var maxRows = sh.getMaxRows(); 
  var lastRow = sh.getLastRow();
  sh.deleteRows(lastRow+1, maxRows-lastRow);
}

注意:如有必要,您可以使用getMaxColumn()getLastColumn()deleteColumns(number, howMany)

以相同方式处理列

修改

顺便说一下,这也是删除电子表格中空行的另一种方法......如果你将两者结合起来,它将完全“清理”你的表格!

function deleteEmptyRows(){ 
  var sh = SpreadsheetApp.getActiveSheet();
  var data = sh.getDataRange().getValues();
  var targetData = new Array();
  for(n=0;n<data.length;++n){
    if(data[n].join().replace(/,/g,'')!=''){ targetData.push(data[n])};
    Logger.log(data[n].join().replace(/,/g,''))
  }
  sh.getDataRange().clear();
  sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);
}

Demo sheet in view only - make a copy to use

答案 1 :(得分:4)

快速说明一下,我添加了这个&#34;如果&#34;保证Serge insas的代码在你试图删除空行时没有空的底行时抛出错误的声明。

  

如果在最后一行函数removeEmptyRows()周围放置它   不会抛出错误:

  if (maxRows-lastRow != 0){
    sh.deleteRows(lastRow+1, maxRows-lastRow);
    }

答案 2 :(得分:4)

在Google表格中删除EmptyRows和removeEmptyColumns的脚本。它汇集了Serge和apptailor之前提到的所有内容。这是sample sheet with the script included文件&gt;制作副本...以编辑工作表的副本。也是video that shows you how to use this sheet

//Remove All Empty Columns in the Entire Workbook
function removeEmptyColumns() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxColumns = sheet.getMaxColumns(); 
var lastColumn = sheet.getLastColumn();
if (maxColumns-lastColumn != 0){
      sheet.deleteColumns(lastColumn+1, maxColumns-lastColumn);
      }
  }
}

//Remove All Empty Rows in the Entire Workbook
function removeEmptyRows() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxRows = sheet.getMaxRows(); 
var lastRow = sheet.getLastRow();
if (maxRows-lastRow != 0){
      sheet.deleteRows(lastRow+1, maxRows-lastRow);
      }
  }
}

答案 3 :(得分:1)

删除所有空行(自下而上)

之前

enter image description here

之后

enter image description here

function isEmptyRow(row){
  for (var columnIndex = 0; columnIndex < row.length; columnIndex++){
    var cell = row[columnIndex];
    if (cell){
      return false;
    }
  }
  return true;
}

function removeEmptyLines(sheet){
  var lastRowIndex = sheet.getLastRow();
  var lastColumnIndex = sheet.getLastColumn();
  var maxRowIndex = sheet.getMaxRows(); 
  var range = sheet.getRange(1, 1, lastRowIndex, lastColumnIndex);
  var data = range.getValues();
  sheet.deleteRows(lastRowIndex+1, maxRowIndex-lastRowIndex);

  for (var rowIndex = data.length - 1; rowIndex >= 0; rowIndex--){
    var row = data[rowIndex];

    if (isEmptyRow(row)){
      sheet.deleteRow(rowIndex + 1);
    }
  }

}


function removeEmptyLinesFromAllSheets(){
  SpreadsheetApp.getActive().getSheets().forEach(removeEmptyLines);
}

仅删除数据下方和上方的空行

之前

enter image description here

之后

enter image description here

function isEmptyRow(row){
  for (var columnIndex = 0; columnIndex < row.length; columnIndex++){
    var cell = row[columnIndex];
    if (cell){
      return false;
    }
  }
  return true;
}

function getFirstNonBlankRowIndex(data){
  for (var rowIndex = 0; rowIndex < data.length; rowIndex++){
    var row = data[rowIndex];

    if (!isEmptyRow(row)){
      return rowIndex;
    }
  }
  return 0;
}

function removePaddedEmptyLines(sheet){
  var lastRowIndex = sheet.getLastRow();
  var lastColumnIndex = sheet.getLastColumn();
  var maxRowIndex = sheet.getMaxRows(); 
  var range = sheet.getRange(1, 1, lastRowIndex, lastColumnIndex);
  var data = range.getValues();
  var firstRowIndex = getFirstNonBlankRowIndex(data);  
  sheet.deleteRows(lastRowIndex+1, maxRowIndex-lastRowIndex);
  sheet.deleteRows(1, firstRowIndex);
}


function removePaddedEmptyLinesFromAllSheets(){
  SpreadsheetApp.getActive().getSheets().forEach(removePaddedEmptyLines);
}

答案 4 :(得分:0)

我已经尝试过这段代码而且效果很好,你可以看看并尝试一下:

function DeleteBlankRows(){
    var sh = SpreadsheetApp.getActiveSheet();
    var maxRows = sh.getMaxRows();
    var lastRow = sh.getLastRow();
    for (var Raw = 1; Raw < sh.getLastRow() ; Raw++)
    {
        if( sh.getRange('A'+Raw).getValue() == '')
        {
            sh.deleteRow(Raw) //deleteRows(lastRow+1, maxRows-lastRow);
        }
    }  

答案 5 :(得分:0)

这对我来说很有效。

function removeEmptyRows(){
      var spreadsheet = SpreadsheetApp.openById("IDOFYOURSPREADSHEETFOUNDINURL");
      var sh = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
      var maxRows = sh.getMaxRows(); 
      var lastRow = sh.getLastRow();
      sh.deleteRows(lastRow+1, maxRows-lastRow);
    }

答案 6 :(得分:0)

此版本允许您指定不想删除的顶部行,并且还可以忽略 ignoreAfterCol 之后的列,以防在查找空白时不考虑某些列:

function removeEmptyLines(sheet,ignoreFirstRows,ignoreAfterCol){
  sheet=ss.getSheetByName('Sheet12')
  //get data and boundaries
  var allData = sheet.getRange(1,1,sheet.getMaxRows(),ignoreAfterCol).getValues();
  var sheetLength = allData.length;
  while(allData[allData.length-1].toString().replace(/,/g,'')=='') allData.pop();
  var lastPopulatedRow = allData.length;

  //delete empty rows from end
  var rowsToDeleteFromEnd = sheetLength - lastPopulatedRow; 
  if(rowsToDeleteFromEnd > 0) sheet.deleteRows(lastPopulatedRow+1,rowsToDeleteFromEnd);

  //iterate through rows and delete blanks one by one
  for(var i=lastPopulatedRow-1; i>ignoreFirstRows; i--){
    if(allData[i].toString().replace(/,/g,'')=='') sheet.deleteRow(i+1);
  }
}