【GAS入門】Googleドキュメントのデータを簡単に取得する方法


Googleドキュメントのデータを取得する方法
以下はGASを使ってドキュメントIDから本文を取得するスクリプトだ。
function getDocumentData() {
const docId = 'YOUR_DOCUMENT_ID_HERE';
const doc = DocumentApp.openById(docId);
const body = doc.getBody();
Logger.log(body.getText());
}
簡単にスクリプトの内容を解説しよう。
openById(docId)は、指定したIDでドキュメントを開くメソッド。
getBody()は、ドキュメントの本文を取得するためのメソッドさ。
getText()は、本文のテキストを取得するメソッドで、ログに出力できるぞ。
試しに、次のGoogleドキュメントの本文の内容を出力してみようか。
https://docs.google.com/document/d/xxxxxxxxxxxxxxxxxxxx/edit?tab=t.0
というURLだから、
xxxxxxxxxxxxxxxxxxxx
がドキュメントIDさね。
ってことで、これを'YOUR_DOCUMENT_ID_HERE'
のところに入れてやると、次のようなログが出るはずだ。

応用:GASでGoogleドキュメントの本文を段落ごとに取得する
Googleドキュメントの本文を内容を部分ごとに分けたり、修正したりすることも可能だ。
function extractAndModify() {
const docId = 'YOUR_DOCUMENT_ID_HERE';
const doc = DocumentApp.openById(docId);
const body = doc.getBody();
const paragraphs = body.getParagraphs();
paragraphs.forEach(paragraph => {
Logger.log(paragraph.getText());
});
}
このスクリプトでは、各段落情報を抽出し順にログに出力できる。
簡単に解説しておこう。
getParagraphs()メソッドは、本文を段落ごとにListとして取得する。
forEach関数で、各段落を順に取得し、ログに出力できるようにする。
練習問題
1. 特定のGoogleドキュメント内のすべての画像のURLを取得するスクリプトを作成してみよう。
2. 各段落の最初に行番号(1, 2, 3, …)を挿入するスクリプトを書いてみよう。
解答・解説
function getImagesUrl() {
const docId = 'YOUR_DOCUMENT_ID_HERE';
const doc = DocumentApp.openById(docId);
const body = doc.getBody();
const images = body.getImages();
images.forEach(image => {
const url = image.getAttributes().get('linkUrl');
Logger.log(url);
});
}
このスクリプトは、ドキュメント内の画像のURLを取得し、ログに出力する。
getImages()メソッドで画像要素を取得し、各画像のURLを「getAttributes().get(‘linkUrl’)」で取得する。
function addLineNumber() {
const docId = 'YOUR_DOCUMENT_ID_HERE';
const doc = DocumentApp.openById(docId);
const body = doc.getBody();
const paragraphs = body.getParagraphs();
paragraphs.forEach((paragraph, index) => {
paragraph.setText((index + 1) + '. ' + paragraph.getText());
});
}
このスクリプトでは、各段落のテキストを取得し、行番号を付加した新しいテキストに更新する。
setText()メソッドで段落の内容を更新し、行番号を付ける。

