Created
December 28, 2022 02:05
-
-
Save simesy/aab11fa362728f3ab3f67292c6ec7241 to your computer and use it in GitHub Desktop.
Splat a 2-dim array of data into an existing sheet, resizing the sheet to match.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wipe a sheet's data completely and replace it with new data. | |
* | |
* The method used will conserve the sheet itself along with | |
* properties of that sheet. Properties could include frozen rows | |
* and some named ranges. | |
* | |
* @param sheetName | |
* Name of the sheet (currently must exist). | |
* @param arrayOfArrays | |
* [['Header one', 'Header two'], ['Cotton Sweatshirt XL', 'css004'], ['Cheese', 'touch']] | |
* All the rows should be a consistent length. | |
*/ | |
function updateSheetWithData(sheetName, arrayOfArrays) { | |
var doc = SpreadsheetApp.getActiveSpreadsheet(); | |
var targetSheet = doc.getSheetByName(sheetName); | |
var sheet_rows = targetSheet.getMaxRows(); | |
var sheet_cols = targetSheet.getMaxColumns(); | |
var data_rows = arrayOfArrays.length; | |
var data_cols = arrayOfArrays[0].length; | |
if (data_rows < sheet_rows) { | |
// Delete rows to match the data. | |
targetSheet.deleteRows(data_rows + 1, sheet_rows - data_rows); | |
} | |
else if (data_rows > sheet_rows) { | |
// Add rows to match the data. | |
targetSheet.insertRowsAfter(sheet_rows, data_rows - sheet_rows); | |
} | |
if (data_cols < sheet_cols) { | |
// Delete columns to match the data. | |
targetSheet.deleteColumns(data_cols + 1, sheet_cols - data_cols); | |
} | |
else if (data_cols > sheet_cols) { | |
// Add columns to match the data. | |
targetSheet.insertColumnsAfter(sheet_cols, data_cols - sheet_cols); | |
} | |
// Paste in the data. | |
let dataRange = targetSheet.getRange(1, 1, data_rows, data_cols); | |
dataRange.setValues(arrayOfArrays); | |
// Repaste as values. | |
arrayOfArrays = dataRange.getValues(); | |
dataRange.setValues(arrayOfArrays); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment