Google Apps Script で差し込み印刷

スプレッドシートのデータをドキュメントに差し込んで、新しいドキュメントを作りたい、というのをやるだけのGoogle Apps Scriptです。これで Google Drive で年賀状印刷みたいなのができるはず。

function myFunction() {
    const templateDocument = DocumentApp.openById("テンプレートとなるドキュメントのID");
    const templateBody = templateDocument.getBody();

    const outputDocument = DocumentApp.create("生成される差し込み印刷したドキュメントの名前");

    const spreadSheet = SpreadsheetApp.openById("差し込まれるデータが入ったスプレッドシートのID");
    const addressSheet = spreadSheet.getSheetByName("差し込まれるデータが入ったシートの名前");

    const values = addressSheet.getDataRange().getValues();
    for (let row_id = 1; row_id < values.length; row_id++) {
        const name = values[row_id][0];
        const school = values[row_id][1];

        const body = templateBody.copy();
        body.replaceText("{name}", name);
        body.replaceText("{school-name}", school);
        appendBody(outputDocument, body);
        return;
    }
}
  
  
/**
 * BodyをまるごとDocumentにコピーする関数
 * @param document 出力先ドキュメント
 * @param body ドキュメントにコピーしたいデータ
 */
function appendBody(document, body) {
    const documentBody = document.getBody();
    const numChildren = body.getNumChildren();
    for (let child_id = 0; child_id < numChildren; child_id++) {
        const element = body.getChild(child_id).copy();
        const type = element.getType();
        if (type === DocumentApp.ElementType.PARAGRAPH) {
            documentBody.appendParagraph(element);
        } else if (type === DocumentApp.ElementType.TABLE) {
            documentBody.appendTable(element);
        } else if (type === DocumentApp.ElementType.LIST_ITEM) {
            documentBody.appendListItem(element);
        } else {
            throw new Error(`Unsupported element type ${type}`);
        }
    }
}