Google Apps Script Ru
Google Apps Script Ru
#google-
apps-script
1
1: google-apps 2
Examples 2
/ 4
, 4
Google Apps 5
2: DriveApp 6
Examples 6
Google 6
Google Mime 6
Google 6
Google 6
- - 7
- - 7
11
Examples 11
Google , 11
4: Firebase AppScript: 12
12
Examples 12
Firebase AppScript 12
Firebase. 14
firebaseURL ? 15
firebaseURL . . 16
. 16
1. , , ,. 16
2. 16
3. 17
4. . 17
5: GmailApp 18
18
Examples 18
CSV, 18
6: SpreadsheetApp 19
19
Examples 19
getActive () - 19
7: Google apps-script 20
20
Examples 20
- Google 20
8: Google MailApp 21
21
Examples 21
MailApp 21
21
22
HTML- 24
9: 27
27
27
27
Examples 27
27
28
10: 29
29
Examples 29
29
30
30
31
11: 32
32
Examples 32
- 32
38
38
Examples 38
forms.html 38
code.gs 39
40
13: DriveApp 43
43
Examples 43
Google 43
Google Mime 43
Google 43
Google blob 44
- - 44
- - 45
14: DriveApp - 46
46
Examples 46
46
15: Google 48
48
Examples 48
48
49
50
Около
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: google-apps-script
It is an unofficial and free google-apps-script ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official google-apps-
script.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ru/home 1
глава 1: Начало работы с скриптом google-
apps
замечания
Официальный обзор для Google Apps Script опубликован по адресу
http://www.google.com/script/start , оттуда
На странице https://developers.google.com/apps-
script/guides/services/#basic_javascript_features
Examples
Для запуска сценариев приложений они должны содержать файл code.gs. Файл code.gs
должен содержать функцию с именем doGet (автономные скрипты) или функцию onOpen (
https://riptutorial.com/ru/home 2
аддон-скрипты). Быстрые запуски в документации содержат примеры.
Если api включен в сценарии приложения, он также должен быть включен в консоли
разработчика. Однако консоль разработчиков содержит api, которая может быть
включена, но не отображается в интерфейсе приложения-скрипта. Например, SDK
Marketplace необходимо включить в консоли разработчиков до того, как приложение
может быть опубликовано в магазине воспроизведения Google или в широкомасштабном
развертывании домена G Suite.
Типы скриптов
• Standalone
• Связано с Google Apps
• Веб-приложения
Автономный скрипт
Веб-приложения
Скрипт Google App Script можно использовать в качестве веб-приложения, так как к нему
можно получить доступ через браузер. Веб-приложение может предоставлять
https://riptutorial.com/ru/home 3
пользовательский интерфейс в браузере и может использовать приложения Google, то
есть документы, листы и т. Д. Оба автономных сценария и скрипты, привязанные к Google
Apps, могут быть превращены в веб-приложения. Для того чтобы любой скрипт работал
как веб-приложение, скрипт должен отвечать двум требованиям:
Функции Inshort, doGet() и doPost() работают как обработчики http get и post request
соответственно.
В вашем коде, если у вас есть несколько функций, перед запуском следует указать
функцию, с которой вы хотите работать. Например :
Кроме того, вы можете нажать ctrl + r с клавиатуры, чтобы запустить код. Он сначала
сохранит код, если не будет сохранен, а затем запустит его. Но для этого вам необходимо
выбрать функцию, как показано на изображении выше.
Кроме того, если ваш сценарий вызывается некоторыми внешними действиями, все же вы
сможете просмотреть журналы, щелкнув view-> logs, если вы регистрируете что-либо после
выполнения кода.
Привет, мир
https://riptutorial.com/ru/home 4
Мы собираемся сказать Hello как окно сообщения.
function helloWorld()
{
Browser.msgBox("Hello World");
}
Чтобы выполнить скрипт, нажмите ▶ или выберите пункт меню « Выполнить» -> helloWorld
Скрипт Google Apps - это платформа, основанная на JavaScript, которая в первую очередь
используется для автоматизации и расширения Google Apps. Скрипт приложений работает
исключительно в инфраструктуре Google, не требующей настройки или конфигурации
сервера. Онлайновая среда IDE служит интерфейсом для всей платформы, соединяющей
все службы, доступные для скриптов приложений. Пользовательская аутентификация
вызывается в платформу через OAuth2 и не требует никакого кода или настройки автором
сценария.
https://riptutorial.com/ru/home 5
глава 2: DriveApp
Examples
function createNewFolderInGoogleDrive(folderName) {
return DriveApp.createFolder(folderName);
}
function createGoogleDriveFileOfMimeType() {
var content,fileName,newFile;//Declare variable names
fileName = "Test File " + new Date().toString().slice(0,15);//Create a new file name with
date on end
content = "This is the file Content";
function createGoogleDriveTextFile() {
var content,fileName,newFile;//Declare variable names
fileName = "Test Doc " + new Date().toString().slice(0,15);//Create a new file name with
date on end
content = "This is the file Content";
https://riptutorial.com/ru/home 6
function createGoogleDriveFileWithBlob() {
var blob,character,data,fileName,i,L,max,min,newFile,randomNmbr;//Declare variable names
fileName = "Test Blob " + new Date().toString().slice(0,15);//Create a new file name with
date on end
function processGoogleDriveFolders() {
var arrayAllFolderNames,continuationToken,folders,foldersFromToken,thisFolder;//Declare
variable names
https://riptutorial.com/ru/home 7
function processGoogleDriveFiles() {
var arrayAllFileNames,continuationToken,files,filesFromToken,fileIterator,thisFile;//Declare
variable names
Logger.log(arrayAllFileNames);
};
if (!child) {
body = "There is no folder";
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), "", "Error Adding Folder!", body)
return;
};
function createNewFolderInGoogleDrive() {
var folder,newFolderName,timeStamp,dateTimeAsString;
newFolderName = 'Test Folder Name ' + dateTimeAsString;//Create new folder name with
date/time appended to name
https://riptutorial.com/ru/home 8
var body,returnedFolder;//Declare variable names
if (!child) {
body = "There is no file";
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), "", "Error Adding File!", body)
return;
};
returnedFolder = DriveApp.addFile(child);
function createNewFileInGoogleDrive() {
var content,file,newFileName,timeStamp,dateTimeAsString;
content = "This is test file content, created at: " + dateTimeAsString;//Create content for
new file
newFileName = 'Test File ' + dateTimeAsString;//Create new file name with date/time appended
to name
function onOpen() {
function getFiles() {
// Look in the same folder the sheet exists in. For example, if this template is in
// My Drive, it will return all of the files in My Drive.
var ssparents = DriveApp.getFileById(ssid).getParents();
var sheet = ss.getActiveSheet();
// Loop through all the files and add the values to the spreadsheet.
var folder = ssparents.next();
var files = folder.getFiles();
var i=1;
https://riptutorial.com/ru/home 9
while(files.hasNext()) {
var file = files.next();
if(ss.getId() == file.getId()){
continue;
}
sheet.getRange(i+1, 1, 1,
4).setValues([[file.getLastUpdated(),file.getOwner().getName(),file.getName(),
file.getUrl()]]);
i++;
}
}
https://riptutorial.com/ru/home 10
глава 3: DriveApp - getFileById (id)
замечания
Также можно получить файл по URL-адресу файла. Идентификатор файла находится в
URL-адресе, поэтому использование идентификатора вместо всего URL означает, что этот
параметр короче. Сохранение URL-адреса, а не идентификатора занимает больше места.
Examples
function getGoogleDriveFileById(id) {
var file;
https://riptutorial.com/ru/home 11
глава 4: Firebase и AppScript: Введение
Вступление
Интегрируйте Firebase с Google AppScript для чтения и записи данных в базе данных
Firebase.
Firebase - это система баз данных NoSQL от Google, которая использует базу данных в
реальном времени для создания и размещения приложений на мобильных, настольных и
планшетных устройствах. Базы данных NoSQL используют объекты JSON для хранения
данных в структурированном формате.
Examples
https://riptutorial.com/ru/home 12
• Теперь в версии выберите стабильную версию общедоступного выпуска.
https://riptutorial.com/ru/home 13
• Нажмите «Сохранить». Теперь Firebase успешно установлена в вашем приложении,
чтобы вы могли работать.
https://riptutorial.com/ru/home 14
• Теперь создадим базу данных в Firebase, используя эту таблицу в листах. Добавьте
следующий код в AppScript.
function writeDataToFirebase() {
var ss = SpreadsheetApp.openById("1LACsj0s3syAa9gvORdRWBhJ_YcXHybjQfHPgw3TLQ6g");
var sheet = ss.getSheets()[0];
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 1; i < data.length; i++) {
var firstName = data[i][0];
var lastName = data[i][1];
dataToImport[firstName + '-' + lastName] = {
firstName:firstName,
lastName:lastName,
emailAddress:data[i][2],
semester:data[i][4],
department:data[i][5],
};
}
var firebaseUrl = "https://example-app.firebaseio.com/";
var secret = "secret-key";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
base.setData("", dataToImport);
}
https://riptutorial.com/ru/home 15
• Перейдите в раздел «Учетные записи службы», где вы можете найти базу данных
URL. Это служит firebaseURL.
• Теперь перейдите на вкладку «Секреты базы данных», и вы можете найти секретный
ключ.
function myFunction(){
var firebaseUrl = "https://example-app.firebaseio.com/";
var secret = "secret-key";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
base.setData("test", "Hello Firebase");
}
function getAllData() {
var firebaseUrl = "https://example-app.firebaseio.com/";
var secret = "secret-key";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
https://riptutorial.com/ru/home 16
var data = base.getData();
for(var i in data) {
Logger.log(data[i].firstName + ' ' + data[i].lastName);
}
}
function getContact() {
var firebaseUrl = "https://example-app.firebaseio.com/";
var secret = "secret-key";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var contact = base.getData("Yash-Udasi");
Logger.log(contact);
}
function updateData() {
var firebaseUrl = "https://example-app.firebaseio.com/";
var secret = "secret-key";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
base.updateData("Yash-Udasi/emailAddress", "yash.udasi@fyuff.com");
}
https://riptutorial.com/ru/home 17
глава 5: GmailApp
замечания
См. Также официальную ссылку API для GmailApp для получения дополнительной
информации о доступных методах.
Examples
function getCsvFromGmail() {
// Get the newest Gmail thread based on sender and subject
var gmailThread = GmailApp.search("from:noreply@example.com subject:\"My daily report\"", 0,
1)[0];
// Get and and parse the CSV from the first attachment
var csv = Utilities.parseCsv(attachments[0].getDataAsString());
return csv;
}
https://riptutorial.com/ru/home 18
глава 6: Активный лист таблицы
SpreadsheetApp
замечания
Метод: getActive ()
Examples
Это возвращает текущую активную электронную таблицу или null, если ее нет.
https://riptutorial.com/ru/home 19
глава 7: Клиент звонит в Google apps-script
Вступление
Google appscript хорошо работает как отдельная платформа и в формате аддона для
документов, листов и форм Google. Тем не менее, есть моменты, когда браузеру браузера
может потребоваться позвонить в приложение Google, чтобы выполнить какое-либо
действие.
Examples
<script src="https://apis.google.com/js/api.js"></script>
<script>
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me',
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
</script>
https://riptutorial.com/ru/home 20
глава 8: Листы Google MailApp
Вступление
Эта служба позволяет пользователям отправлять электронные письма с полным
контролем над содержимым электронной почты. В отличие от GmailApp, единственная
цель MailApp - отправлять электронную почту. MailApp не может получить доступ к
почтовому ящику Gmail пользователя.
Examples
MailApp - это api из Google App Script, который можно использовать для отправки почты
function sendEmails() {
function checkQuota() {
Logger.log(MailApp.getRemainingDailyQuota());
}
function getSheetData() {
https://riptutorial.com/ru/home 21
var startRow = 2; // First row of data to process
var numRows = 100; // Number of rows to process
var startCol = 1; //First column of data to process
var numCols = 15; // Number of columns to process
return data;
}
function getDataSheet() {
sheet = SpreadsheetApp.getActiveSheet();
return data;
}
https://riptutorial.com/ru/home 22
function getDataSheet() {
sheet = SpreadsheetApp.getActiveSheet();
return data;
}
function sendEmail() {
//Sheet range starts from index 1 and data range starts from index 0
sheet.getRange(1 + i, emailCol).setValue(emailSent);
}
}
}
https://riptutorial.com/ru/home 23
Отправка HTML-содержимого по почте
https://riptutorial.com/ru/home 24
Теперь обновите метод getMessage () из приведенного выше примера следующим образом:
return message;
}
https://riptutorial.com/ru/home 25
function getDataSheet() {
sheet = SpreadsheetApp.getActiveSheet();
return data;
}
return message;
}
function sendEmail() {
sheet.getRange(startRow + i, emailCol).setValue(emailSent);
}
}
}
https://riptutorial.com/ru/home 26
глава 9: Меню добавления таблиц
Синтаксис
1. addMenu (имя, subMenus)
параметры
название Описание
замечания
Обычно вам нужно вызвать addMenu из функции onOpen, чтобы меню автоматически
создавалось при загрузке электронной таблицы.
activeSheet.addMenu("addMenuExample", menuEntries);
}
Examples
https://riptutorial.com/ru/home 27
activeSheet.addMenu("addMenuExample", menuEntries);
/*
*/
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('My HR')
.addItem('Send Form to All', 'sendIDPForm_All')
.addItem('Trigger IDP System', 'applyCategory')
.addToUi();
}
https://riptutorial.com/ru/home 28
глава 10: Обслуживание электронных
таблиц
замечания
Официальную ссылку API для службы электронных таблиц можно найти на странице
https://developers.google.com/apps-script/reference/spreadsheet/ .
Examples
Простынь
Вставить колонку
Вставить строку
Значение ячейки
https://riptutorial.com/ru/home 29
var spread_sheet = SpreadsheetApp.getActiveSpreadsheet();
var active_sheet = spread_sheet.getActiveSheet();
var cell = range.getCell(1, 1);
var cell_value = cell.getValue();
cell.setValue(100);
Копировать ячейки
формула
Представьте, что у нас есть отдельная электронная таблица Google, и нам нужно получить
значение ячейки B2 в ячейке D5 на вашем текущем листе.
function copyValueandPaste()
{
var source = SpreadsheetApp.openById('spread sheet id is here'); //Separate spreadsheet
book
var sourcesheet = source.getSheetByName('Sheet1'); //Sheet tab with source data
var sourceCellValue = sourcesheet.getRange('B2').getValue(); // get B2 cell value
https://riptutorial.com/ru/home 30
}
}
}
Обратите внимание, что это добавит строку после последней непустой строки.
var newRowIndex = 2;
var row = ["Gandalf", "?", "Wizard", "?", 2019];
someSheet.insertRowBefore(newRowIndex);
// getRange(row, col, numRows, numCols)
someSheet.getRange(newRowIndex, 1, 1, row.length).setValues([row]); // Note 2D array!
https://riptutorial.com/ru/home 31
глава 11: Приложения для скриптов
приложений
замечания
Это примерное веб-приложение формы, бит на стороне клиента показывает некоторый
базовый дизайн UX, такой как отключенная кнопка отправки при отправке формы или
сообщение об ошибке, если она не работает ... и т. Д.
Битовый скрипт приложений очень прост. Он содержит только код, необходимый для
обслуживания html, и для проверки поля.
• Code.gs
• index.html
• Stylesheet.html
• JavaScript.html
Examples
Форма веб-приложения
Скрипт приложений:
//Called from the client with form data, basic validation for blank values
function formSubmit(formData){
for(var field in formData){
if(formData[field] == ''){
return {success: false, message: field + ' Cannot be blank'}
}
}
return {success: true, message: 'Sucessfully submitted!'};
}
https://riptutorial.com/ru/home 32
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://ssl.gstatic.com/docs/script/css/add-ons1.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
type="text/javascript"></script>
</head>
<body>
<div id="mainForm">
<h1>Example Form</h1>
<form>
<div>
<div class="inline form-group">
<label for="name">Name</label>
<input id="nameInput" style="width: 150px;" type="text">
</div>
</div>
<div>
<div class="inline form-group">
<label for="city">City</label>
<input id="cityInput" style="width: 150px;" type="text">
</div>
<div class="inline form-group">
<label for="state">State</label>
<input id="stateInput" style="width: 40px;" type="text">
</div>
<div class="inline form-group">
<label for="zip-code">Zip code</label>
<input id="zip-codeInput" style="width: 65px;" type="number">
</div>
</div>
<div class="block form-group">
<label for="typeSelect">Type</label>
<select id="typeSelect">
<option value="">
</option>
<option value="Type 1 ">
Type 1
</option>
<option value="Type 2 ">
Type 2
</option>
<option value="Type 3 ">
Type 3
</option>
<option value="Type 4 ">
Type 4
</option>
</select>
</div>
<button class="action" id="submitButton" type="button">Submit</button>
<button class="clear" id="clearFormButton" type="button">Clear Form</button>
</form>
<div class="hidden error message">
<div class="title">Error:</div>
<div class="message"></div>
https://riptutorial.com/ru/home 33
</div>
<div class="hidden success message">
<div class="title">Message:</div>
<div class="message">Sucessfully submitted</div>
</div>
</div>
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</body>
</html>
CSS
<style>
.hidden {
display: none;
}
.form-group {
margin: 2px 0px;
}
#submitButton {
margin: 4px 0px;
}
body {
margin-left: 50px;
}
.message {
padding: 2px;
width: 50%;
}
.message > * {
display: inline-block;
}
.message .title {
font-weight: 700;
font-size: 1.1em;
}
.success.message {
border: 1px solid #5c9a18;
background: #e4ffe4;
color: #2a8e2a;
}
.error.message {
background: #f9cece;
border: 1px solid #7d2929;
}
.error.message .title {
color: #863030;
}
https://riptutorial.com/ru/home 34
button.clear {
background: -moz-linear-gradient(top, #dd6e39, #d17636);
background: -ms-linear-gradient(top, #dd6e39, #d17636);
background: -o-linear-gradient(top, #dd6e39, #d17636);
background: -webkit-linear-gradient(top, #dd6e39, #d17636);
background: linear-gradient(top, #dd6e39, #d17636);
border: 1px solid transparent;
color: #fff;
text-shadow: 0 1px rgba(0, 0, 0, .1);
}
button.clear:hover {
background: -moz-linear-gradient(top, #ca602e, #bd6527);
background: -ms-linear-gradient(top, #ca602e, #bd6527);
background: -o-linear-gradient(top, #ca602e, #bd6527);
background: -webkit-linear-gradient(top, #ca602e, #bd6527);
background: linear-gradient(top, #ca602e, #bd6527);
border: 1px solid transparent;
color: #fff;
text-shadow: 0 1px rgba(0, 0, 0, .1);
}
</style>
JavaScript
<script>
var inputs = [
'nameInput',
'cityInput',
'stateInput',
'zip-codeInput',
'typeSelect'
];
$(function(){
var pageApp = new formApp();
$('#submitButton').on('click', pageApp.submitForm);
$('#clearFormButton').on('click', pageApp.clearForm);
});
google.script.run
https://riptutorial.com/ru/home 35
.withSuccessHandler(self.sucessfullySubmitted)
.withFailureHandler(self.failedToSubmit)
.formSubmit(self.getFormData());
};
//Sets the general message box's message and enables or disabled the error box
function setSuccessMessage(show, message){
if(show){
$('.success.message').removeClass('hidden');
$('.success.message .message').text(message);
} else {
$('.success.message').addClass('hidden');
$('.success.message .message').text('');
}
}
//Sets the error message box's message and enables or disabled the error box
function setErrorMessage(show, message){
if(show){
$('.error.message').removeClass('hidden');
$('.error.message .message').text(message);
} else {
$('.error.message').addClass('hidden');
$('.error.message .message').text('');
}
}
function getFormData(){
var output = {};
https://riptutorial.com/ru/home 36
for(var i = 0; i < inputs.length; i++){
output[inputs[i]] = $('#'+inputs[i]).val();
}
return output;
}
</script>
https://riptutorial.com/ru/home 37
глава 12: Скрипт Google Web App для
автоматической загрузки с Google Диска
Вступление
Этот простой веб-скрипт Google App (автономный) позволяет Google Диску повторять
опрос для файлов, которые будут загружены на локальный ПК пользователя. Показывает,
как использовать один скрипт приложения для предоставления функции как: 1.
Пользовательского интерфейса (простой в этом примере). 2. Страница загрузки файла.
Для более полного объяснения того, как это работает, прочитайте пример «Как это
работает».
замечания
Веб-скрипт должен быть опубликован для работы.
Examples
forms.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
setInterval(
function ()
{
document.getElementById('messages').innerHTML = 'Event Timer Fetching';
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.fetchFromGoogleDrive();
}, 60000);
function callFetchGoogleDrive() {
document.getElementById('messages').innerHTML = 'Fetching';
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.fetchFromGoogleDrive();
}
function onSuccess(sHref)
{
https://riptutorial.com/ru/home 38
if(new String(sHref).valueOf() == new String("").valueOf())
{
document.getElementById('messages').innerHTML = 'Nothing to download';
}
else
{
document.getElementById('messages').innerHTML = 'Success';
document.getElementById('HiddenClick').href = sHref;
document.getElementById('HiddenClick').click(); // Must enable Pop Ups for
https://script.google.com
}
}
function onFailure(error)
{
document.getElementById('messages').innerHTML = error.message;
}
</script>
</head>
<body>
<div id="messages">Waiting to DownLoad!</div>
<div>
<a id="HiddenClick" href="" target="_blank" onclick="google.script.host.close"
style="visibility: hidden;">Hidden Click</a>
</div>
<div>
<button type="button" onclick='callFetchGoogleDrive();' id="Fetch">Fetch Now!</button>
</div>
</body>
</html>
code.gs
function doGet(e){
var serveFile = e.parameter.servefile;
var id = e.parameter.id;
if(serveFile)
{
return downloadFile(id); // and Hyde
}
if (fileslist.hasNext()) {
var afile = fileslist.next();
var html = ScriptApp.getService().getUrl()+"?servefile=true&id="+afile.getId();
return html;
}
else
{
return '';
}
https://riptutorial.com/ru/home 39
}
Второй механизм позволяет вернуть URL-адрес скрипта (самого себя) или URL-адрес
файла Drive. URL-адрес файла накопителя не очень полезен, поскольку его нельзя
напрямую использовать в клиентском браузере для загрузки файла. Размещение этого url
в привязке (и нажатии на него) приводит к открытию веб-страницы, но фактически ничего
не делает (кроме, возможно, просмотра файла в Интернете).
Это оставляет URL-адрес скрипта. Однако скрипт url предоставляет только скрипт, а не
файл.
Чтобы инициировать загрузку, файл из службы Диска должен быть возвращен из функции
https://riptutorial.com/ru/home 40
doGet / doPost сценария на стороне сервера, используя ContentService createTextOutput
точно так, как показано в онлайн-руководствах Google. Однако это означает, что на веб-
странице не может быть другого элемента пользовательского интерфейса,
сгенерированного результатами, возвращаемыми doGet / doPost.
Этот сценарий использует подход д-ра Джекила и г-на Хайд для решения этой проблемы.
Если скрипт открывается с параметром servefile = true, скрипт ведет себя как загрузка
файла диска.
Это приводит к запуску другого вызова приложения / скрипта. Когда новый вызов
приложения запускает doGet, он обнаружит параметр servefile и вместо того, чтобы
возвращать пользовательский интерфейс, он вернет файл в браузер. Возвращенный файл
будет идентифицирован параметром ID, который был ранее возвращен описанным выше
поиском.
https://riptutorial.com/ru/home 41
новый вызов приложения закроется, оставив первый вызов, чтобы повторить этот процесс.
Прочитайте Скрипт Google Web App для автоматической загрузки с Google Диска онлайн:
https://riptutorial.com/ru/google-apps-script/topic/8212/скрипт-google-web-app-для-
автоматической-загрузки-с-google-диска
https://riptutorial.com/ru/home 42
глава 13: Служба DriveApp
замечания
Типы Mime Google не могут использоваться для третьего параметра Mime Types.
Использование типа Mime Google приведет к ошибке:
MimeType.GOOGLE_APPS_SCRIPT
MimeType.GOOGLE_DOCS
MimeType.GOOGLE_DRAWINGS
MimeType.GOOGLE_FORMS
MimeType.GOOGLE_SHEETS
MimeType.GOOGLE_SLIDES
Examples
function createNewFolderInGoogleDrive() {
var folderName,newFolder;//Declare variable names
function createGoogleDriveFileOfMimeType() {
var content,fileName,newFile;//Declare variable names
fileName = "Test File " + new Date().toString().slice(0,15);//Create a new file name with
date on end
content = "This is the file Content";
https://riptutorial.com/ru/home 43
function createGoogleDriveTextFile() {
var content,fileName,newFile;//Declare variable names
fileName = "Test Doc " + new Date().toString().slice(0,15);//Create a new file name with
date on end
content = "This is the file Content";
function createGoogleDriveFileWithBlob() {
var blob,character,data,fileName,i,L,max,min,newFile,randomNmbr;//Declare variable names
fileName = "Test Blob " + new Date().toString().slice(0,15);//Create a new file name with
date on end
function processGoogleDriveFolders() {
var arrayAllFolderNames,continuationToken,folders,foldersFromToken,thisFolder;//Declare
variable names
https://riptutorial.com/ru/home 44
the continuation token is working
function processGoogleDriveFiles() {
var arrayAllFileNames,continuationToken,files,filesFromToken,fileIterator,thisFile;//Declare
variable names
Logger.log(arrayAllFileNames);
};
https://riptutorial.com/ru/home 45
глава 14: Служба DriveApp - файлы по типу
и строке поиска
параметры
Examples
function mainSearchFunction(searchStr) {
var fileInfo,arrayFileIDs,arrayFileNames,arrayOfIndexNumbers,
allFileIDsWithStringInName,i,searchStr,thisID;//Declare variables
if (!searchStr) {
searchStr = "Untitled";//Assign a string value to the variable
};
allFileIDsWithStringInName = [];
arrayFileIDs = fileInfo[0];
for (i=0;i<arrayOfIndexNumbers.length;i+=1) {
thisID = arrayFileIDs[arrayOfIndexNumbers[i]];
allFileIDsWithStringInName.push(thisID);
};
Logger.log(allFileIDsWithStringInName)
};
function getFilesOfType() {
var allFormFiles,arrFileName,arrFileID,arrFileUrls,thisFile;
allFormFiles = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
arrFileName = [];
arrFileID = [];
arrFileUrls = [];
while (allFormFiles.hasNext()) {
https://riptutorial.com/ru/home 46
thisFile=allFormFiles.next();
arrFileName.push(thisFile.getName());
arrFileID.push(thisFile.getId());
arrFileUrls.push(thisFile.getUrl());
};
//Logger.log(arrFileName)
return [arrFileID,arrFileName];
};
function searchFileNamesForString(arrayFileNames,searchStr) {
var arrayIndexNumbers,i,L,thisName;
arrayIndexNumbers = [];
L = arrayFileNames.length;
for (i=0;i<L;i+=1){
thisName = arrayFileNames[i];
Logger.log(thisName);
Logger.log('thisName.indexOf(searchStr): ' + thisName.indexOf(searchStr));
return arrayIndexNumbers;
};
https://riptutorial.com/ru/home 47
глава 15: Создание пользовательской
функции для Google Таблиц
Вступление
Пользовательская функция в документах google привязана к определенному документу (и,
следовательно, может использоваться только в этом документе).
Examples
/**
* Returns the standard gravity constant in the specified acceleration units
* Values taken from https://en.wikipedia.org/wiki/Standard_gravity on July 24, 2016.
*
* @param {number} input 1 for cm/s², 2 for ft/s², 3 for m/s²
*
* @customfunction
*/
function sg(units_key) {
var value;
switch(units_key) {
case 1:
value = 980.665;
break;
case 2:
value = 32.1740;
break;
case 3:
value = 9.80665;
break;
default:
throw new Error('Must to specify 1, 2 or 3');
}
return value;
}
https://riptutorial.com/ru/home 48
формуле ячейки.
Основной пример
/**
* Divides n by d unless d is zero, in which case, it returns
* the given symbol.
*
* @param {n} number The numerator
* @param {d} number The divisor
* @param {symbol} string The symbol to display if `d == 0`
* @return {number or string} The result of division or the given symbol
*
* @customfunction
*/
function zeroSafeDivide(n, d, symbol) {
if (d == 0)
return symbol;
else
return n / d;
}
https://riptutorial.com/ru/home 49
кредиты
S.
Главы Contributors
No
DriveApp -
3 Sandy Good
getFileById (id)
Firebase и
4 Joseba, Vishal Vishwakarma
AppScript: Введение
5 GmailApp nibarius
Активный лист
6 таблицы iJay
SpreadsheetApp
Клиент звонит в
7 Supertopoz
Google apps-script
Листы Google Bhupendra Piprava, Brian, Jordan Rhea, Kos, nibarius, Saloni
8
MailApp Vithalani
Меню добавления
9 Bishal, iJay, nibarius
таблиц
Обслуживание
10 электронных cdrini, iJay, nibarius, Sandy Good, sudo bangbang
таблиц
Приложения для
11 скриптов Douglas Gaskell
приложений
https://riptutorial.com/ru/home 50
13 Служба DriveApp Sandy Good
Служба DriveApp -
14 файлы по типу и nibarius, Sandy Good
строке поиска
Создание
пользовательской
15 Francky_V, Joshua Dawson, Pierre-Marie Richard, Rubén
функции для
Google Таблиц
https://riptutorial.com/ru/home 51