1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GASでスプレッドシートからドキュメントへ出力

Last updated at Posted at 2021-09-13

GASでスプレッドシートからドキュメントへ出力

業務で引っかかったので、覚書。
画像のサイズ設定で引っかかった。
外部ライブラリのimgAppで解決した。

準備

あらかじめスプレッドシートへファイルIDなどを起こしておく。
A列 名前 B列 詳細情報 C列画像のファイルIDとしておく。


/**
 * スプレッドシートの内容をテキストファイルへ出力
 */
function outputTextFile() {
  // 出力するフォルダのID(出力先のフォルダIDを設定)
  const folderId = 'フォルダID';

  // 出力するファイル名
  const Name = "出力ファイル名.txt"
  const doc = DocumentApp.create(Name);
  const body = doc.getBody();

  // アクティブなスプレッドシートを取得
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  // アクティブなシートを取得
  const sheet = spreadsheet.getActiveSheet();

  // 最終行を取得
  const lastRow = sheet.getLastRow();

  for (let i = 1; i <= lastRow; i++) {

    // テキストに出力する範囲のデータを取得
    let imageName = sheet.getRange(i, 1).getValue();
    let description = sheet.getRange(i, 2).getValue();
    let imageId = sheet.getRange(i, 3).getValue();
    let blob = DriveApp.getFileById(imageId).getBlob();

    // 画像の縦横比を取得
    let res = ImgApp.getSize(blob);
    let width = res.width;
    let height = res.height;

    // 節の名称を14pxで最終行へ挿入
    let addImageName = body.appendParagraph(imageName);
    addImageName.editAsText().setFontSize(14);

    // 説明を11pxで最終行へ挿入
    let addDescription = body.appendParagraph(description);
    addDescription.editAsText().setFontSize(11);
    
    // 画像を横300pxでアスペクト比を揃えて大きさを編集し最終行へ挿入
    body.appendImage(blob).setWidth(300).setHeight(300 * height / width);

  } // for i
}

appendImage() で最終行へ画像を出力することができる。
アスペクト比を保ったまま縮小したかったが、setWidth() , setHeight() はpxで指定する必要があったので、先に縦横の長さを取得している。

参考

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?