

この記事について

Google Apps Script(GAS)でGoogleドキュメントを操作する時の良く使う構文を集めました。随時更新中です。
Google Apps Scriptの作成方法
Google Apps Scriptをはじめて作成する方は、スクリプトを作成する方法について下記の記事で解説していますのでご覧ください。

GoogleドキュメントのDocumentAppクラスの階層について

GoogleドキュメントをGASで扱うには下記のDocumentAppクラスの階層構造を知っておく必要があります。
- DocumentApp
- body
- Paragraph(パラグラフ:段落)
- text
- 表
- 画像
- Paragraph(パラグラフ:段落)
- body
基本構文
既存のGoogleドキュメントを開く(スタンドアローンスクリプト)
//Googleドキュメントを開きます。下記のどちらかで開きます。 var doc = DocumentApp.openById("ID"); var doc = DocumentApp.openByUrl("url");
既存のGoogleドキュメントを開く(コンテナバインドスクリプトのみで使用可)
//現在開いているアクティブなGoogleドキュメントを取得します。 var doc = DocumentApp.getActiveDocument();
コンテナバインドとスタンドアローンって何?
コンテナバインドスクリプトとスタンドアローンスクリプトって何?という方は下記の記事で解説していますので参考になさってください。

Googleドキュメントを新規作成する
//Googleドキュメントを新規作成する。引数はファイル名を渡します。 var doc = DocumentApp.create('Sample Document');
テキストを編集する
var paragraphs = body.getParagraphs(); var p1 = paragraphs[0] //段落にテキストを挿入する。 p1.insertText( 0, "text" ); //段落にテキストを追加する。 p1.appendText("text");
Googleドキュメントを保存する
Goolgeドキュメントをブラウザで普通に手作業で操作する場合、基本的に即時的に変更が確定されるので保存操作は特に必要ありませんが、GASで操作する時は明示的にsaveコマンドで保存しないと変更内容が反映しないことがあります。
var doc = DocumentApp.openById("ここにファイルを入れます”); doc.saveAndClose();
ドキュメントファイル名を取得する。
var doc = DocumentApp.getActiveDocument(); doc.getBlob().getName(); //拡張子ありのファイル名。 doc.getName(); //上と一緒。拡張子なしのファイル名。
ドキュメントファイル名を変更する。
//ファイル名をテストドキュメントに変更します。 var doc = DocumentApp.getActiveDocument(); doc.setName("テストドキュメント");
ログを出力する
Logger.log("hello, world.")
良く使うGoogleドキュメントのGASコード集
Googleドライブの指定のフォルダに新規Googleドキュメントを作成する
var folder = DriveApp.getFolderById("folderId"); var doc = DocumentApp.create("doc name"); var docFile = DriveApp.getFileById(doc.getId()); folder.addFile(docFile);
テンプレートとなるGoogleドキュメントをもとにコピーを作成する
function fileCopy(){ //ファイル名に挿入する日付部分を作成します。 var date = new Date(); date.setDate(date.getDate() + 7); var formattedDate = Utilities.formatDate(date, "JST", "yyyyMMdd"); var fileName = "ドキュメントファイル名"; //コピー元のファイルを取得します。 var sourcefile = DriveApp.getFileById("1dUOUuuaqZquWwC_Z1NMrGh6mkUp79EngxbOvXpjeOl4"); //コピーを作成します。 newfile = sourcefile.makeCopy(fileName + "_" + formattedDate); //コピー後のファイルを取得します。 var doc = DocumentApp.openById(newfile.getId()); Logger.log(doc.getName()); }
文章の最後に文章を追記する
var body = DocumentApp.getActiveDocument().getBody(); body.appendPageBreak();//ページ区切りを入れる body.appendParagraph("hogehoge");//段落をアペンドする
文章の最初に文章を挿入追記する
var body = DocumentApp.getActiveDocument().getBody(); body.insertParagraph(0, "hogehoge"); //段落番号を0が文章の最初
段落ごとに処理する
ドキュメントを翻訳する例
//段落ごとに翻訳してみる。 var body = DocumentApp.getActiveDocument().getBody(); var paragraphs = body.getParagraphs(); var textBefore ; // 翻訳前テキスト var textTranslated ; // 翻訳後テキスト paragraphs.forEach( p => { textBefore = p.getText(); if (textBefore != ""){ textTranslated = LanguageApp.translate(textBefore, "ja", "en"); p.setText(textTranslated); };
表を差し込む
function createDoc() { var doc = DocumentApp.create('Sample Document'); var body = doc.getBody(); var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']]; body.insertParagraph(0, doc.getName()) .setHeading(DocumentApp.ParagraphHeading.HEADING1); table = body.appendTable(rowsData); table.getRow(0).editAsText().setBold(true); }
文字列置換(テンプレート文字列による置換)
Googleドキュメントの操作は、長い文章を扱うことが多いのでJavascriptのテンプレート文字列を使って置換すると楽になるシーンが多いかなと思います。
//Googleドキュメントに予め入力してある文字列を置換します。 //下記の例では、Googleドキュメントに予め{name},{address},{city},{zip}という文字列を設置してあります。 //それを連想配列で作成したお客様情報に変換しています。 function searchAndReplace() { var body = DocumentApp.getActiveDocument() .getBody(); var client = { name: 'お客様 タロウ', address: '新宿', city: '東京', zip: 'xxx-xxxx' }; body.replaceText('{name}', client.name); body.replaceText('{address}', client.address); body.replaceText('{city}', client.city); body.replaceText('{zip}', client.zip); }
▲テンプレート文字列を使った文字列変換の使い方についてはコチラをご覧ください。
現在のカーソル位置に文章を挿入する
var doc = DocumentApp.getActiveDocument(); doc.getCursor().insertText(text); //getcusorはアクティブドキュメントにしか使用できない
関連記事




Google Apps Scriptを学ぶには?
GAS初学者の方がテキスト1冊買うならこれ一択です。幅開く網羅されているので基本が身に付きます。
動画で学ぶならコチラがおすすめです。UdemyのGAS講座はいくつかありますが、他の講座と比較しても圧倒的レビュー数と高評価です。万が一の返金保証があるので安心して購入ができます。
▲Google Apps Scriptの入門書として間違いのない一冊です。ノンプログラマーの方にもわかりやすく解説されています。V8ランライム対応版にアップデート済みため情報も新しいです。
▲こちらGoogle Apps Scriptの本ではないですが、Google Workspace(旧G Suite)を自動化したりアプリ化するには、Google AppSheetという選択肢もあります。Google AppSheetはノーコードでアプリを作成できます。
▲Google for Educationの使い方にとどまらず実際の運用ででてくる問題への対処方法などもかかれていて面白いです。教師の方達の共著なので現実的な内容となっています。