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で指定する必要があったので、先に縦横の長さを取得している。
参考