स्प्रेडशीट में मौजूद डेटा हटाना

कोडिंग का लेवल: बीच के लेवल वाला
कुल समय: 20 मिनट
प्रोजेक्ट टाइप: एडिटर ऐड-ऑन

मकसद

  • समझें कि समाधान क्या है.
  • जानें कि Apps Script सेवा के अंदर क्या काम करती है.
  • स्क्रिप्ट सेट अप करें.
  • स्क्रिप्ट चलाएं.

इस सलूशन के बारे में जानकारी

स्प्रेडशीट से डेटा साफ़ करने के लिए, खाली पंक्तियों और कॉलम को अपने-आप हटाएं. स्प्रेडशीट को डेटा रेंज के किनारों पर काटें, और डेटा की गैप को पूरी करें.

स्प्रेडशीट को फ़ॉर्मैट करने के लिए, ऐड-ऑन का इस्तेमाल करने का डेमो

यह कैसे काम करता है

स्क्रिप्ट नीचे दिए गए काम करती है:

  • खाली पंक्तियों को मिटाना–किसी चुनी गई रेंज में, स्क्रिप्ट खाली पंक्तियों की पहचान करके उन्हें मिटा देती है. अगर किसी पंक्ति के सेल में स्पेस के वर्ण हैं, तो उस पंक्ति को खाली नहीं माना जाता.
  • खाली कॉलम मिटाएं–किसी चुनी गई रेंज में, स्क्रिप्ट खाली कॉलम की पहचान करके उन्हें मिटा देती है. अगर किसी कॉलम के सेल में स्पेस के वर्ण हैं, तो उस कॉलम को खाली नहीं माना जाता.
  • शीट को डेटा रेंज के मुताबिक काटें–स्क्रिप्ट यह पता लगाती है कि डेटा रेंज कहां खत्म होती है. साथ ही, अतिरिक्त पंक्तियों और कॉलम को मिटा देती है.
  • खाली पंक्तियां भरें–स्क्रिप्ट, चुने गए चालू सेल के कॉन्टेंट को कॉपी करके उसके नीचे की खाली सेल में चिपका देती है. स्क्रिप्ट खाली न होने वाली या डेटा रेंज के आखिर तक पहुंचने पर, कॉन्टेंट को चिपकाना बंद कर देती है.

Apps Script सेवाएं

यह समाधान इस सेवा का इस्तेमाल करता है:

ज़रूरी शर्तें

इस सैंपल का इस्तेमाल करने के लिए, आपको ये ज़रूरी शर्तें पूरी करनी होंगी:

  • Google खाता (Google Workspace खातों के लिए एडमिन की अनुमति ज़रूरी हो सकती है).
  • इंटरनेट ऐक्सेस करने वाला वेब ब्राउज़र.

स्क्रिप्ट सेट अप करें

  1. साफ़ शीट वाला Apps Script प्रोजेक्ट खोलने के लिए, नीचे दिए गए बटन पर क्लिक करें.
    प्रोजेक्ट खोलें
  2. खास जानकारी पर क्लिक करें .
  3. खास जानकारी देने वाले पेज पर, कॉपी बनाएं पर क्लिक करें कॉपी बनाने के लिए आइकॉन.
  4. कॉपी किए गए प्रोजेक्ट में सबसे ऊपर, डिप्लॉय करें > डिप्लॉयमेंट की जांच करें पर क्लिक करें.
  5. चुनें कि टाइप के बगल में, डिप्लॉयमेंट टाइप चालू करें प्रोजेक्ट सेटिंग का आइकॉन > एडिटर ऐड-ऑन पर क्लिक करें.
  6. नया टेस्ट बनाएं पर क्लिक करें.
  7. जांच के लिए दस्तावेज़ में जाकर, कोई दस्तावेज़ नहीं चुना गया पर क्लिक करें.
  8. उस स्प्रेडशीट को चुनें जिसमें डेटा मौजूद है, जिसे हटाना है. इसके बाद, शामिल करें पर क्लिक करें. सैंपल दस्तावेज़ का इस्तेमाल करने के लिए, सैंपल क्लीनअप डेटा स्प्रेडशीट की एक कॉपी बनाएं.
  9. टेस्ट सेव करें पर क्लिक करें.
  10. स्प्रेडशीट खोलने के लिए, सेव किए गए जांच के बगल में मौजूद रेडियो बटन को चुनें और लागू करें पर क्लिक करें.

स्क्रिप्ट चलाएं

  1. स्प्रेडशीट में, A1:F20 रेंज चुनें.
  2. एक्सटेंशन > साफ़ शीट की कॉपी > खाली पंक्तियां मिटाएं पर क्लिक करें.
  3. जब कहा जाए, तब जारी रखें पर क्लिक करें और स्क्रिप्ट को अनुमति दें.
  4. एक्सटेंशन > साफ़ शीट की कॉपी > खाली पंक्तियों को मिटाएं पर फिर से क्लिक करें.
  5. एक्सटेंशन > साफ़ शीट की कॉपी > खाली कॉलम मिटाएं पर क्लिक करें.
  6. एक्सटेंशन > साफ़ शीट की कॉपी > शीट को डेटा रेंज में काटें पर क्लिक करें.
  7. C7 सेल चुनें.
  8. एक्सटेंशन > क्लीन शीट की कॉपी > नीचे खाली पंक्तियां भरें पर क्लिक करें.

कोड की समीक्षा करें

इस समाधान के Apps Script कोड की समीक्षा करने के लिए, नीचे सोर्स कोड देखें पर क्लिक करें:

सोर्स कोड देखें

Code.gs

solutions/editor-add-on/clean-sheet/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/add-ons/clean-sheet

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Application Constants
const APP_TITLE = 'Clean sheet';

/**
 * Identifies and deletes empty rows in selected range of active sheet.
 * 
 * Cells that contain space characters are treated as non-empty.
 * The entire row, including the cells outside of the selected range,
 * must be empty to be deleted.
 *  
 * Called from menu option.
 */
function deleteEmptyRows() {

  const sheet = SpreadsheetApp.getActiveSheet();

  // Gets active selection and dimensions.
  let activeRange = sheet.getActiveRange();
  const rowCount = activeRange.getHeight();
  const firstActiveRow = activeRange.getRow();
  const columnCount = sheet.getMaxColumns();

  // Tests that the selection is a valid range.
  if (rowCount < 1) {
    showMessage('Select a valid range.');
    return;
  }
  // Tests active range isn't too large to process. Enforces limit set to 10k.
  if (rowCount > 10000) {
    showMessage("Selected range too large. Select up to 10,000 rows at one time.");
    return;
  }

  // Utilizes an array of values for efficient processing to determine blank rows.
  const activeRangeValues = sheet.getRange(firstActiveRow, 1, rowCount, columnCount).getValues();

  // Checks if array is all empty values.
  const valueFilter = value => value !== '';
  const isRowEmpty = (row) => {
    return row.filter(valueFilter).length === 0;
  }

  // Maps the range values as an object with value (to test) and corresponding row index (with offset from selection).
  const rowsToDelete = activeRangeValues.map((row, index) => ({ row, offset: index + activeRange.getRowIndex() }))
    .filter(item => isRowEmpty(item.row)) // Test to filter out non-empty rows.
    .map(item => item.offset); //Remap to include just the row indexes that will be removed.

  // Combines a sorted, ascending list of indexes into a set of ranges capturing consecutive values as start/end ranges.
  // Combines sequential empty rows for faster processing.
  const rangesToDelete = rowsToDelete.reduce((ranges, index) => {
    const currentRange = ranges[ranges.length - 1];
    if (currentRange && index === currentRange[1] + 1) {
      currentRange[1] = index;
      return ranges;
    }
    ranges.push([index, index]);
    return ranges;
  }, []);

  // Sends a list of row indexes to be deleted to the console.
  console.log(rangesToDelete);

  // Deletes the rows using REVERSE order to ensure proper indexing is used.
  rangesToDelete.reverse().forEach(([start, end]) => sheet.deleteRows(start, end - start + 1));
  SpreadsheetApp.flush();
}

/**
 * Removes blank columns in a selected range.
 * 
 * Cells containing Space characters are treated as non-empty.
 * The entire column, including cells outside of the selected range,
 * must be empty to be deleted.
 *   
 * Called from menu option.
 */
function deleteEmptyColumns() {

  const sheet = SpreadsheetApp.getActiveSheet();

  // Gets active selection and dimensions.
  let activeRange = sheet.getActiveRange();
  const rowCountMax = sheet.getMaxRows();
  const columnWidth = activeRange.getWidth();
  const firstActiveColumn = activeRange.getColumn();

  // Tests that the selection is a valid range.
  if (columnWidth < 1) {
    showMessage('Select a valid range.');
    return;
  }
  // Tests active range is not too large to process. Enforces limit set to 1k.
  if (columnWidth > 1000) {
    showMessage("Selected range too large. Select up to 10,000 rows at one time.");
    return;
  }

  // Utilizes an array of values for efficient processing to determine blank columns.
  const activeRangeValues = sheet.getRange(1, firstActiveColumn, rowCountMax, columnWidth).getValues();

  // Transposes the array of range values so it can be processed in order of columns.
  const activeRangeValuesTransposed = activeRangeValues[0].map((_, colIndex) => activeRangeValues.map(row => row[colIndex]));

  // Checks if array is all empty values.
  const valueFilter = value => value !== '';
  const isColumnEmpty = (column) => {
    return column.filter(valueFilter).length === 0;
  }

  // Maps the range values as an object with value (to test) and corresponding column index (with offset from selection).
  const columnsToDelete = activeRangeValuesTransposed.map((column, index) => ({ column, offset: index + firstActiveColumn}))
    .filter(item => isColumnEmpty(item.column)) // Test to filter out non-empty rows.
    .map(item => item.offset); //Remap to include just the column indexes that will be removed.

  // Combines a sorted, ascending list of indexes into a set of ranges capturing consecutive values as start/end ranges.
  // Combines sequential empty columns for faster processing.
  const rangesToDelete = columnsToDelete.reduce((ranges, index) => {
    const currentRange = ranges[ranges.length - 1];
    if (currentRange && index === currentRange[1] + 1) {
      currentRange[1] = index;
      return ranges;
    }
    ranges.push([index, index]);
    return ranges;
  }, []);

  // Sends a list of column indexes to be deleted to the console.
  console.log(rangesToDelete);

  // Deletes the columns using REVERSE order to ensure proper indexing is used.
  rangesToDelete.reverse().forEach(([start, end]) => sheet.deleteColumns(start, end - start + 1));
  SpreadsheetApp.flush();
}

/**
 * Trims all of the unused rows and columns outside of selected data range.
 * 
 * Called from menu option.
 */
function cropSheet() {
  const dataRange = SpreadsheetApp.getActiveSheet().getDataRange();
  const sheet = dataRange.getSheet();

  let numRows = dataRange.getNumRows();
  let numColumns = dataRange.getNumColumns();

  const maxRows = sheet.getMaxRows();
  const maxColumns = sheet.getMaxColumns();

  const numFrozenRows = sheet.getFrozenRows();
  const numFrozenColumns = sheet.getFrozenColumns();

  // If last data row is less than maximium row, then deletes rows after the last data row.
  if (numRows < maxRows) {
    numRows = Math.max(numRows, numFrozenRows + 1); // Don't crop empty frozen rows.
    sheet.deleteRows(numRows + 1, maxRows - numRows);
  }

  // If last data column is less than maximium column, then deletes columns after the last data column.
  if (numColumns < maxColumns) {
    numColumns = Math.max(numColumns, numFrozenColumns + 1); // Don't crop empty frozen columns.
    sheet.deleteColumns(numColumns + 1, maxColumns - numColumns);
  }
}

/**
 * Copies value of active cell to the blank cells beneath it. 
 * Stops at last row of the sheet's data range if only blank cells are encountered.
 * 
 * Called from menu option.
 */
function fillDownData() {

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  // Gets sheet's active cell and confirms it's not empty.
  const activeCell = sheet.getActiveCell();
  const activeCellValue = activeCell.getValue();

  if (!activeCellValue) {
    showMessage("The active cell is empty. Nothing to fill.");
    return;
  }

  // Gets coordinates of active cell.
  const column = activeCell.getColumn();
  const row = activeCell.getRow();

  // Gets entire data range of the sheet.
  const dataRange = sheet.getDataRange();
  const dataRangeRows = dataRange.getNumRows();

  // Gets trimmed range starting from active cell to the end of sheet data range.
  const searchRange = dataRange.offset(row - 1, column - 1, dataRangeRows - row + 1, 1)
  const searchValues = searchRange.getDisplayValues();

  // Find the number of empty rows below the active cell.
  let i = 1; // Start at 1 to skip the ActiveCell.
  while (searchValues[i] && searchValues[i][0] == "") { i++; }

  // If blanks exist, fill the range with values.
  if (i > 1) {
    const fillRange = searchRange.offset(0, 0, i, 1).setValue(activeCellValue)
    //sheet.setActiveRange(fillRange) // Uncomment to test affected range.
  }
  else {
    showMessage("There are no empty cells below the Active Cell to fill.");
  }
}

/**
 * A helper function to display messages to user.
 * 
 * @param {string} message - Message to be displayed.
 * @param {string} caller - {Optional} text to append to title.
 */
function showMessage(message, caller) {

  // Sets the title using the APP_TITLE variable; adds optional caller string.
  const title = APP_TITLE
  if (caller != null) {
    title += ` : ${caller}`
  };

  const ui = SpreadsheetApp.getUi();
  ui.alert(title, message, ui.ButtonSet.OK);
}

solutions/editor-add-on/clean-sheet/Menu.js
/**
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Creates a menu entry in the Google Sheets Extensions menu when the document is opened.
 *
 * @param {object} e The event parameter for a simple onOpen trigger. 
 */
function onOpen(e) {
  // Builds a menu that displays under the Extensions menu in Sheets.
  let menu = SpreadsheetApp.getUi().createAddonMenu()

  menu
    .addItem('Delete blank rows (from selected rows only)', 'deleteEmptyRows')
    .addItem('Delete blank columns (from selected columns only)', 'deleteEmptyColumns')
    .addItem('Crop sheet to data range', 'cropSheet')
    .addSeparator()
    .addItem('Fill in blank rows below', 'fillDownData')
    .addSeparator()
    .addItem('About', 'aboutApp')
    .addToUi();
}

/**
 * Runs when the add-on is installed; calls onOpen() to ensure menu creation and
 * any other initializion work is done immediately. This method is only used by 
 * the desktop add-on and is never called by the mobile version.
 *
 * @param {object} e The event parameter for a simple onInstall trigger. 
 */
function onInstall(e) {
  onOpen(e);
}

/**
 * About box for context and developer contact information.
 * TODO: Personalize
 */
function aboutApp() {
  const msg = `
  Name: ${APP_TITLE}
  Version: 1.0
  Contact: <Developer Email Goes Here>`

  const ui = SpreadsheetApp.getUi();
  ui.alert("About this application", msg, ui.ButtonSet.OK);
}

योगदानकर्ता

Google, इस सैंपल को मैनेज करने के लिए Google Developer के विशेषज्ञों की मदद लेता है.

अगले चरण