【GAS】Google Apps Script 活用事例 Googleドキュメントで、装飾を一括適用させる方法
Photo by Gus Moretta on Unsplash
一括で!!というのが、自動化の醍醐味だと思っています。今回はGASで文字を太くしたり、線を引いたり、そういった処理を一括でこなすスクリプトを紹介したいと思います。結構難しい.....。paragraphやtextの概念などの違いがスッと入ってこない.....。
特定の単語の色を一括で、変更する方法
タスクと入力すると、タスクという単語だけが、緑に変更されます。こちらは、GAS本に記載があったものを、そのまま使わせてもらっています。
この処理のソースコード
function detectWords() {
const document = DocumentApp.getActiveDocument();
const body = document.getBody();
const paragraphs = body.getParagraphs();
const targetWord = getInput('一括処理をしたい単語を入力してください。');
let result = null;
let count = 0;
while(result = body.findText(targetWord, result)){
const text = result.getElement().asText();
console.log(text);
text.setForegroundColor('#00ab44');
count += 1
}//while
console.log(`該当する文言を、${count} 件、色の変換をしました。`);
}
function getInput(text) {
const ui = DocumentApp.getUi();
const response = ui.prompt(
text,
'',
ui.ButtonSet.OK
);
const input = response.getResponseText()
console.log(input);
switch (response.getSelectedButton()) {
case ui.Button.OK:
console.log('%s と入力され、OKが押されました。',input);
break;
case ui.Button.CLOSE:
console.log('閉じるボタンが押されました。');
}//switch
return input
}
文章全体にスタイルを一括で適用させるスクリプト
手順10までを連番で、書き出すスクリプトです。ヒラギノの指定がやっぱり効かない。おそらく、Googleドキュメントがデフォルトで、サポートしているフォントではないと、変更が出来ないのかもしれません。ヒラギノはMacに入っているフォントであって、デフォルトでは使えないから?
function setStyle(){
const body = DocumentApp.getActiveDocument().getBody();
let style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Hiragino Kaku Gothic ProN';
style[DocumentApp.Attribute.FONT_SIZE] = 18;
style[DocumentApp.Attribute.BOLD] = true;
style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#00ab44';
for(let i = 0; i < 10; i++){
// Append a plain paragraph.
const number = i + 1;
const par = body.appendParagraph(`手順 ${number}. `);
// Apply the custom style.
par.setAttributes(style);
}//for
}//end
特定の単語を挿入し、1行全体の色を変える
function editAsText() {
const document = DocumentApp.getActiveDocument();
const body = document.getBody();
const text = body.editAsText();
//位置の指定が出来る。appendTextは最後に追加する。
text.insertText(0, 'Inserted text.\n');
const paragraphs = body.getParagraphs();
const length = paragraphs[0].getText().length;
text.setForegroundColor(0, length, '#00FFFF');
}
こんなの自動化して、何になるんだって自分でも言いたくなってしまうのですが、千里の道も一歩からってヤツですね。
どうやら、ドキュメントだと、While文を使う機会が増えそうな気がしています。while文、普段あんまり使わないから苦手です.....。検索対象のキーワードが無くなるまで、処理を続けるみたいな感じです。
Google Driveのフォルダ書き出す時に使ったけど、それっきり....復習しなきゃ。
この記事が気に入ったらサポートをしてみませんか?