LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

2024年5月18日土曜日

Googleドライブのファイルを指定フォルダに移動したい - Move a file to a specific folder in Google Drive via Apps Script


Googleドライブのファイル移動を簡単にしたくて書いたコードです。
I wrote this code to make it easier to move files in Google Drive.


移動したいファイルURLと移動先のフォルダURLを入力して移動するWebアプリです。
Deploy a web app to move a file using the file URL and the destination folder URL.

実行手順 - Execution procedure:
  1. file URL に移動したいファイルのURLを入力する - Set the "file URL"
  2. folder URLには移動先のフォルダのURLを入力する- Set the "folder URL"
  3. submitボタンをクリックする- Click the "submit" button



Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}

function moveFile(fileId, folderId) {
const file = DriveApp.getFileById(fileId);
const destinationFolder = DriveApp.getFolderById(folderId);
file.moveTo(destinationFolder);
return "Success!!";
}


index.html
<!DOCTYPE html>
<html>
<body>
file URL:<input type="text" id="fileUrl">
folder URL:<input type="text" id="folderUrl">
<button id="submit">submit</button>

<script>
elem("submit").onclick = submitClicked;

function submitClicked() {
const fileId = elem("fileUrl").value.split("/d/")[1].split("/")[0];
const folderId = elem("folderUrl").value.split("/folders/")[1];
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.moveFile(fileId, folderId);
}

function onSuccess(result) {
alert(result);
}

function onFailure(e) {
alert([e.message, e.stack]);
}

function elem(id) {
return document.getElementById(id);
}

</script>
</body>
</html>


Reference

GoogleドライブのファイルやフォルダをmoveTo(destination)で移動したい

2024年5月17日金曜日

英文に含まれる単語のペアを作りたい - Create word pairs from a sentence


以前、上記のリンク先では組み合わせのパターンを出力するコードを書きました。
In a previous article, I wrote about generating combination patterns of elements within an array.


今回は、配列内の先頭の要素から順番にペアを作っていくコードです。
This time, the code creates pairs sequentially in the array from the first element.


例として、英文に含まれる単語のペアを作ってみます。
I try to write code to create word pairs from an English sentence.


入力する英文の例 - Example Input sentence

「I will create word pairs from a sentence.」


出力するペアの例 - Example Output pairs

[I will, will create, create word, word pairs, pairs from, from a, a sentence.]



Code.gs
function getPairs() {
const text = "I will create word pairs from a sentence.";
const words = text.split(" ");
Logger.log(words);
let pairs = [];
for(let i = 0; i < words.length-1; i++) {
const pair = words[i] + " " + words[i+1];
pairs.push(pair);
}
Logger.log(pairs);
}


Logger.log


Tips

すべて小文字にして、不要な記号を含まないようにしたくてコードを追加しました。
I added code to make all letters lowercase and remove unnecessary symbols.


value.match(/[a-zA-Z0-9'\s-]/g, "")
アルファベット(大文字・小文字)、数字、シングルクォート、スペース、ハイフンのみ抽出する。
Extract only uppercase and lowercase letters, numbers, single quotes, spaces, and hyphens.


このように取得したい
Getting results like this.
[i will, will create, create word, word pairs, pairs from, from a, a sentence]

I → i
sentence. → sentence

function getPairs() {
const text = "I will create word pairs from a sentence.";
const value = extractChar(text).toLowerCase();
const words = value.split(" ");
Logger.log(words);
let pairs = [];
for(let i = 0; i < words.length-1; i++) {
const pair = words[i] + " " + words[i+1];
pairs.push(pair);
}
Logger.log(pairs);
}

function extractChar(value) {
return value.match(/[a-zA-Z0-9'\s-]/g, "").join("");
}

Logger.log


Reference

String.prototype.toLowerCase()


2024年5月16日木曜日

Google Slidesの表にSpreadsheetから値を入れたい - Insert Spreadsheet values into a Slides table


以前の記事では、スライド上にダイアログを作って表に値を入力するというのをやりました。
In a previous article, I created a dialog on a slide and used it to input values into a table.


今回は、スプレッドシートから値を取得して、それをスライドの表の中へ入力するというのを試しました。
This time, I tried retrieving values from a spreadsheet and inserting them into a table in a slide.



Spreadsheet
Slideに渡すのはシートのB2:E5に入力されている値
Insert the values from range B2:E5 in the Sheet into the Slides table.



Slide
スライドには、5列5行の表を配置しておく
Place a 5x5 table on the slide.

2列目2行目以降に上記シートの値を入力する←Code.gsはこれをやる
Insert the values starting at the second row and second column of the table.←Code.gs



Code.gs
function setValuesToSlideFromSheet() {
const sheetUrl = "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit#gid=SHEET_ID";
const slideUrl = "https://docs.google.com/presentation/d/SLIDE_ID/edit#slide=id.PAGE_ID";

const sheet = returnSheet(sheetUrl);
const startRow = 2;
const startCol = 2;
const numRows = 4;
const numCols = 4;
const range = sheet.getRange(startRow, startCol, numRows, numCols);
const values = range.getValues();

const page = returnPage(slideUrl);
const table = page.getTables()[0];
setValuesInTable(table, values, 1, 1);
}

function returnSheet(sheetUrl) {
const spreadsheet = SpreadsheetApp.openByUrl(sheetUrl);
const sheetId = sheetUrl.split("/edit#gid=")[1];
const sheets = spreadsheet.getSheets();
for (let i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetId() == sheetId) {
return spreadsheet.getSheets()[i];
}
}
}

function returnPage(slideUrl) {
const slide = SlidesApp.openByUrl(slideUrl);
const slideId = slideUrl.split("/edit#slide=id.")[1];
const pages = slide.getSlides();
for(let i = 0; i < pages.length; i++) {
if(pages[i].getObjectId() == slideId) {
return slide.getSlides()[i];
}
}
}

function setValuesInTable(table, values, startRow = 0, startCol = 0) {
for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row + startRow < table.getNumRows() && col + startCol < table.getNumColumns()) {
table.getCell(row + startRow, col + startCol).getText().setText(values[row][col]);
}
}
}
}

sheetUrlとslideUrlを書き換えて、setValuesToSlideFromSheet()を実行すると、startRow, startCol, numRows, numCols で設定した範囲内にあるシートの値がSlideの表に入力されます。
After changing sheetUrl and slideUrl in Code.gs and executing setValuesToSlideFromSheet(), the values within the sheet range specified by startRow, startCol, numRows, and numCols will be inserted into the table on the Slide.


Tips

今回使うデータの作成にはGeminiを利用しました。
The data in this example was generated by Gemini.

INPUT
get
take
make
give
上記の英語について、一行ずつ以下を行ってください。
1. 日本語訳
2. Part of Speech: v. adv. adj. など品詞の短縮形
3. short description: 短い一文の英文で説明してください。
OUTPUT例 それぞれ以下の形で一行で書いてください。
get: 得る: Part of Speech: Short description

OUTPUT
get: 得る: v.: To obtain or receive something.
take: 取る: v.: To carry or move something from one place to another.
make: 作る: v.: To create or produce something.
give: 与える: v.: To offer or hand over something to someone.



A列にOUTPUTを貼り付けて、B列に=split(A2,": ",false)のような関数を入れるとB,C,D,E列に値が入ります。
By pasting the OUTPUT into column A and entering a function like =split(A2, ": ", false) in column B, the values will be split and placed into columns B, C, D, and E.


Reference

Google Apps Scriptでスライド内のページIDを取得したい(.getObjectId)

Google Slidesの表をApps Scriptで取得したい - Get tables in Slides

Google Slidesの表に値を入れたい Insert values into the specific table

シートIDを渡してシートを取得する

Google Slidesのダイアログから表に値を入力したい - Input values from dialog to table

Google Slidesのダイアログから表に値を入力したい2 - Input values from dialog to table 2

2024年5月15日水曜日

Google Slidesのダイアログから表に値を入力したい2 - Input values from dialog to table 2


上記のリンク先で以前書いたコードの応用バージョンです。
This is a variation of the code I previously wrote at the link above.



今回やること- What I will do this time
  1. 5つの表をスライドに配置する - Place four tables on the slide.
  2. スライドにダイアログを表示する - Display a dialog on the slide.
  3. ダイアログにテキストを入力する - Enter text into the dialog.
  4. submitボタンをクリックする - Click the submit button.
  5. 入力されたテキストを分割する - Split the entered text.
  6. 5つの表にテキストを入力する - Input the text into the five tables.

今回の例では、4つの英単語 get, take, make, give の類義語と日本語訳をダイアログに入力し、それをよしなに分割して5つの表に入力します。
In this example, I will input synonyms and Japanese translations for the four English words (get, take, make, give) into a dialog, split them appropriately, and input them into five tables.



今回使うスライドの例
An example of the slide used for this demonstration.

左に4行1列の表を配置
Place a table with 4 rows and 1 column on the left.

右に4行2列の表(1行目はセルを結合)を縦に4つ配置
Vertically place four tables to the right, each with 4 rows and 2 columns
(with the first row's cells merged).



Code.gs
function modalessTemplate() {
const htmlOutput = HtmlService
.createTemplateFromFile("index")
.evaluate()
.setWidth(720)
.setHeight(180);
SlidesApp.getUi().showModelessDialog(htmlOutput, "MyGUI");
}

function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

function setValuesForTables(records) {
const tables = getPageTables();
const recordsObj = returnRecordsObj(records);
setValuesInTable(tables[0], recordsObj["headings"]);
for(let i = 1; i < 5; i++) {
const table = tables[i];
const values = recordsObj["arrays"][i-1] ;
setValuesInTable(table, values);
}
}

function getPageTables() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSelection().getCurrentPage();
const tables = slide.getTables();
return tables;
}

function returnRecordsObj(records) {
let headings = [];
let arrays = [];
for(let i = 0; i < records.length; i++) {
let values = [];
const units = records[i].split("」");
const unit0 = units[0].split("「")
const unit1 = units[1].split("「")
const unit2 = units[2].split("「")
const unit3 = units[3].split("「")
values = [
[unit0[1]],
[unit1[0],unit1[1]],
[unit2[0],unit2[1]],
[unit3[0],unit3[1]]
]
headings.push([unit0[0]]);
arrays.push(values);
}
const obj = {
"headings": headings,
"arrays": arrays
}
return obj;
}

function setValuesInTable(table, values) {
for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row < table.getNumRows() && col < table.getNumColumns()) {
table.getCell(row, col).getText().setText(values[row][col]);
}
}
}
}


index.html
<!DOCTYPE html>
<html>
<head>
<?!= include("css"); ?>
</head>
<body>
<textarea id="input"></textarea>
<br>
<button id="submit">submit</button>
<?!= include("JavaScript"); ?>
</body>
</html>


css.html
<style>
#input {
font-size: 12px;
width: 95vw;
height: 60vh;
}
</style>


JavaScript.html
<script>
function elem(id) {
return document.getElementById(id);
}

elem("submit").onclick = submitClicked;

function submitClicked() {
const records = elem("input").value.split("\n");
google.script.run.setValuesForTables(records);
}
</script>


Code.gsのmodalessTemplate() を実行すると以下のダイアログがスライドの前面に表示されます。
Running modalessTemplate() in Code.gs will display the following dialog in front of the slide.
ダイアログのテキストエリアに以下のテキストを入力します
Enter the following text into the text area of the dialog:
get「得る」obtain「手に入れる」receive「受け取る」acquire「獲得する」
take「取る」grab「つかむ」seize「奪う」capture「捕らえる」
make「作る」create「創造する」produce「生産する」build「建てる」
give「与える」offer「提供する」donate「寄付する」bestow「授ける」



submitボタンをクリックすると、表の指定したセルにテキストが入力されます。
Clicking the submit button will input the text into the specified cell of the table.


Tips

ダイアログに入力するテキストはGeminiに作ってもらいました。
The text for the dialog was generated by Gemini.

INPUT
get, take, make, give それぞれの英単語について、それぞれ3つずつ類義語を教えて下さい。その日本語訳も横に書いてください。例のように横に並べてください。
例 get「得る」類義語1「日本語訳1」類義語2「日本語訳2」類義語3「日本語訳3」

OUTPUT
get「得る」 obtain「手に入れる」 receive「受け取る」 acquire「獲得する」
take「取る」 grab「つかむ」 seize「つかむ、奪う」 capture「捕らえる、獲得する」
make「作る」 create「創造する」 produce「生産する」 build「建てる、築く」
give「与える」 offer「提供する」 donate「寄付する」 bestow「授ける」



そのテキストをreturnRecordsObj(records)で以下のように分けた obj を返します。
The text is split appropriately via returnRecordsObj(records) and returns an object like the following:

const obj = {
  "headings":[
    ["get"],["take"],["make"],["give"]
  ],
  "arrays":[
    [["得る"],["obtain","手に入れる"],["receive","受け取る"],["acquire","獲得する"]],
    [["取る"],["grab","つかむ"],["seize","奪う"],["capture","捕らえる"]],
    [["作る"],["create","創造する"],["produce","生産する"],["build","建てる"]],
    [["与える"],["offer","提供する"],["donate","寄付する"],["bestow","授ける"]]
  ]
}


Reference

Google Slidesのダイアログから表に値を入力したい - Input values from dialog to table

2024年5月14日火曜日

Google Slidesのダイアログから表に値を入力したい - Input values from dialog to table


Google Slidesでダイアログから表に値を入力したくて書いたコードです。
I wrote code to input values from a dialog into a table in Google Slides.



今回使うスライドの例
An example of the slide used for this demonstration.

4行1列の表を配置しておきます。
Place a table with 4 rows and 1 column in Google Slides.



Code.gs
function modalessTemplate() {
const htmlOutput = HtmlService
.createTemplateFromFile("index")
.evaluate()
.setWidth(360)
.setHeight(240);
SlidesApp.getUi().showModelessDialog(htmlOutput, "MyGUI");
}

function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

function setValuesForTables(records) {
const table = getPageTables()[0];
setValuesInTable(table, records);
}

function getPageTables() {
const presentation = SlidesApp.getActivePresentation();
const slide = presentation.getSelection().getCurrentPage();
const tables = slide.getTables();
return tables;
}

function setValuesInTable(table, values) {
for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row < table.getNumRows() && col < table.getNumColumns()) {
table.getCell(row, col).getText().setText(values[row][col]);
}
}
}
}


index.html
<!DOCTYPE html>
<html>
<head>
<?!= include("css"); ?>
</head>
<body>
<textarea id="input"></textarea>
<br>
<button id="submit">submit</button>
<?!= include("JavaScript"); ?>
</body>
</html>


css.html
<style>
#input {
font-size: 15px;
width: 95vw;
height: 60vh;
}
</style>


JavaScript.html
<script>
function elem(id) {
return document.getElementById(id);
}

elem("submit").onclick = submitClicked;

function submitClicked() {
const records = elem("input").value.split("\n");
google.script.run.setValuesForTables(records);
}
</script>


modalessTemplate() を実行するとダイアログが表示されます。
Running modalessTemplate() will display a dialog.


ダイアログに
1
2
3
4
のように改行区切りで値を入力してsubmitボタンをクリックします。
Enter the values in the dialog, separated by newlines, and click the Submit button.


テーブルに値が入力されます。
The values are inserted into the table.


Reference

Google SlidesでDialogを表示したい

Google Slidesの表をApps Scriptで取得したい - Get tables in Slides

Google Slidesの表に値を入れたい Insert values into the specific table

2024年5月13日月曜日

Google Slidesの表でセルの書式を設定したい - Format cells in a table


Googleスライドに配置した表で、セルの書式を設定するコードを試しました。
I tried to apply formatting to the cells in a table in Google Slides using Apps Script.
  • セルの文字色:  Font color
  • 太字:  Bold
  • 文字サイズ: Font size
  • 背景色: Background color
  • 垂直中央: Vertical alignment
  • 水平中央:  Horizontal alignment



今回使うスライドの例
An example of the slide used for this demonstration.



Code.gs
function formatCells() {
var presentation = SlidesApp.getActivePresentation();
var slide = presentation.getSelection().getCurrentPage();
var tables = slide.getTables();

var table = tables[0];
var numRows = table.getNumRows();
var numCols = table.getNumColumns();

for (var i = 0; i < numRows; i++) {
for (var j = 0; j < numCols; j++) {
var cell = table.getCell(i, j);
var textStyle = cell.getText().getTextStyle();
textStyle.setForegroundColor('#ffffff');// fontColor
textStyle.setBold(true);// bold
textStyle.setFontSize(14);// fontSize

cell.getFill().setSolidFill('#0000cd');// backgroundColor
cell.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);// verticalAlign
cell.getText().getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);// horizontalAlign
}
}
}


formatCells()を実行すると、コードで設定したように表の見た目を変更できました。
Running formatCells() successfully changed the appearance of the table as specified in the code.


Tips

ChatGPT4とGeminiに質問した回答を参考にしましたが、セル内の水平方向の中央揃えは一発で書いてくれず、何度も調整が必要でした。
It took multiple attempts to achieve successful horizontal centering of text within cells, as neither ChatGPT-4 nor Gemini provided a working solution in one go.

cell.getText().getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);// horizontalAlign


ContentAlignmentは垂直方向のみ設定できるらしい
It seems that ContentAlignment can only be used for vertical alignment.

cell.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);// verticalAlign



Format cells in a table within Google Slides using Apps Script.

Reference

Google Slidesの表をApps Scriptで取得したい - Get tables in Slides


Class Table > getCell(rowIndex, columnIndex)

Class TableCell > getText()

Class TableCell > getFill()

Class TableCell > setContentAlignment(contentAlignment)

Class TextRange > getTextStyle()

Class TextRange > getParagraphStyle()

Class ParagraphStyle > setParagraphAlignment(alignment)

Class TextStyle > setForegroundColor

Class TextStyle > setBold(bold)

Class TextStyle > setFontSize(fontSize)

Google Slidesの表に値を入れたい Insert values into the specific table


Googleスライドの表に値を入れたくて試したコードです。
I tried to input values into a table in Google Slides via Apps Script.


Google Slidesで現在選択している表に値を入れたい - Insert values into the active table と似ていますが、表をコード内で指定するところが今回やりたいことです。
It's similar to an article I wrote before, but this time I want to specify the table within the code.



今回使うスライドの例
An example of the slide used for this demonstration.



Code.gs
function insertValuesIntoTable() {
var presentation = SlidesApp.getActivePresentation();
var slide = presentation.getSelection().getCurrentPage();
var tables = slide.getTables();
var table = tables[0];
var values = [
['Value 1', 'Value 2', 'Value 3'],
['Value 4', 'Value 5', 'Value 6'],
['Value 7', 'Value 8', 'Value 9']
];
for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row < table.getNumRows() && col < table.getNumColumns()) {
table.getCell(row, col).getText().setText(values[row][col]);
}
}
}
}


insertValuesIntoTable() を実行すると、0番目の表の中に、Code.gs内で指定した値(Value 1〜9)が入力されます。
Running insertValuesIntoTable() will fill the table index 0 with the values specified in the Code.gs (Value 1 through 9).


Reference

Google Slidesで現在選択している表に値を入れたい - Insert values into the active table

Google Slidesで現在選択している表に値を入れたい - Insert values into the active table


Google Slidesで、選択している表に値を入れるというのをGoogle Apps Scriptで試しました。
I tried using Google Apps Script to input values into a selected table in Google Slides.



今回使うスライドの例
An example of the slide used for this demonstration.



Code.gs
function insertValuesIntoSelectedTable() {
var presentation = SlidesApp.getActivePresentation();
var selection = presentation.getSelection();
var pageElement = selection.getPageElementRange().getPageElements()[0];
var table = pageElement.asTable();
var values = [
['Value 1', 'Value 2', 'Value 3'],
['Value 4', 'Value 5', 'Value 6'],
['Value 7', 'Value 8', 'Value 9']
];
for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row < table.getNumRows() && col < table.getNumColumns()) {
table.getCell(row, col).getText().setText(values[row][col]);
}
}
}
}


insertValuesIntoSelectedTable() を実行すると、選択した表の中に、Code.gs内で指定した値(Value 1〜9)が入力されます。
Running insertValuesIntoSelectedTable() will fill the selected table with the values specified in the Code.gs (Value 1 through 9).


Tips

上記のCode.gsは、ChatGPT4 に質問した回答をコンパクトにしたものです。
The Code.gs above is a compact version of the answer I got from ChatGPT4.


ChatGPT4が書いてくれたスクリプトの例
A script example written by ChatGPT4.


Reference


Google Slidesの表をApps Scriptで取得したい - Get tables in Slides

Latest post

Googleドライブのファイルを指定フォルダに移動したい - Move a file to a specific folder in Google Drive via Apps Script

Googleドライブのファイル移動を簡単にしたくて書いたコードです。 I wrote this code to make it easier to move files in Google Drive. 移動したいファイルURLと移動先のフォルダURLを入力して移動するWebアプ...