forked from erickoledadevrel/crop-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.js
79 lines (72 loc) · 2.16 KB
/
Code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Crop Sheet add-on for Google Sheets. Allows users to remove excess rows and columns
* from their spreadsheet based on the current selection or the cells that have data.
* @OnlyCurrentDoc
*/
/**
* Adds a menu when the spreadsheet is opened.
*/
function onOpen() {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Crop to data', 'cropToData')
.addItem('Crop to selection', 'cropToSelection')
.addToUi();
}
/**
* Adds a menu after the add-on is installed.
*/
function onInstall() {
onOpen();
}
/**
* Crops the current sheet to the user's selection.
*/
function cropToSelection() {
var range = SpreadsheetApp.getActiveSheet().getActiveRange();
cropToRange(range);
}
/**
* Crops the current sheet to the data.
*/
function cropToData() {
var range = SpreadsheetApp.getActiveSheet().getDataRange();
cropToRange(range);
}
/**
* Crops the sheet such that it only contains the given range.
* @param {SpreadsheetApp.Range} range The range to crop to.
*/
function cropToRange(range) {
var sheet = range.getSheet();
var spreadsheet = sheet.getParent();
var firstRow = range.getRow();
var lastRow = firstRow + range.getNumRows() - 1;
var firstColumn = range.getColumn();
var lastColumn = firstColumn + range.getNumColumns() - 1;
var maxRows = sheet.getMaxRows();
var maxColumns = sheet.getMaxColumns();
if (lastRow < maxRows) {
sheet.deleteRows(lastRow + 1, maxRows - lastRow);
}
if (firstRow > 1) {
sheet.deleteRows(1, firstRow - 1);
}
if (lastColumn < maxColumns) {
sheet.deleteColumns(lastColumn + 1, maxColumns - lastColumn);
}
if (firstColumn > 1) {
sheet.deleteColumns(1, firstColumn - 1);
}
sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate();
showCompleteMessage(spreadsheet);
}
/**
* Shows a message to the user when the cropping is complete.
* @param {SpreadsheetApp.Spreadsheet} spreadsheet The spreadsheet to show the message on.
*/
function showCompleteMessage(spreadsheet) {
var title = 'Crop Sheet';
var message = HtmlService.createHtmlOutputFromFile('CompleteMessage').getContent();
var timeoutSeconds = 8;
spreadsheet.toast(message, title, timeoutSeconds);
}