LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Monday, August 15, 2022

Google SpreadsheetのnotesをDocumentに書き出したい


Google SpreadsheetのnotesをまとめてDocumentに書き出したくて書いたコードです。

実行プロセス
  1. getSheetNotes():noteを取得したいシートの範囲を指定して取得します
  2. notes.join("\n"):取得したデータ(配列)を改行でつないで文字列にします
  3. createSingleSentence(str):一文ごとに分けます
    • str.replace(/(?<![a-zA-Z0-9!?])[\s ](?![a-zA-Z0-9!?])/g, ""):英数以外の不要な半角スペースを削除(もとの文章に不要な半角がなければ省略)
    • .replace(/。/g, "。\n\n"):すべての「。」のあとに改行2つ追加
  4. addTextToDocument(singleSentences):指定したドキュメントに書き出します



コード.gs
function writeNotesToDocument() {
  const notes = getSheetNotes();
  const str = notes.join("\n");
  const singleSentences = createSingleSentence(str);
  addTextToDocument(singleSentences);
}

function getSheetNotes() {
  const ssUrl = "SPREADSHEET_URL";
  const ss = SpreadsheetApp.openByUrl(ssUrl);
  const sh = ss.getSheets()[0];
  const col = "E";
  const startRow = 2;
  const endRow = 378;
  const range = sh.getRange(col + startRow + ":" + col + endRow);
  const notes = range.getNotes();
  Logger.log(notes);
  return notes;
}

function createSingleSentence(str) {
  const sigleSentence = str.replace(/(?<![a-zA-Z0-9!?])[\s ](?![a-zA-Z0-9!?])/g, "").replace(/。/g, "。\n\n");
  return sigleSentence;
}

function addTextToDocument(text) {
  const url = "DOCUMENT_URL";
  const doc = DocumentApp.openByUrl(url);
  const body = doc.getBody();
  body.appendParagraph(text);
}


参考

スプレッドシートのノートを取得する

Googleドキュメントにテキストを追加したい

正規表現で英数以外のテキストの間にある半角スペースを削除したい

Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...