LoginSignup
0
1

More than 3 years have passed since last update.

【GAS】フィルタ後のデータを取得して貼り付け

Posted at

前提

GAS(V8)を使用して、スプレッドシートのフィルタ後のデータを取得。その後、別シートに貼り付けする方法を備忘録として記載。

手順

/**
 * Rawシートの最終列に1がセットされているデータのみを抽出してDupliシート(新規作成)に貼り付ける。
 */
function onlyDupliRaw() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ssRaw = ss.getSheetByName('Raw');

  let lastRow = ssRaw.getLastRow();
  let lastCol = ssRaw.getLastColumn();

  // フィルタを設定
  let rule = SpreadsheetApp.newFilterCriteria()
    .whenNumberEqualTo(1) // 数値1と同値を抽出
    .build();
  ssRaw.getDataRange().createFilter().setColumnFilterCriteria(lastCol, rule);

  /**
   * 「Dupli」シートに「Raw」からフィルタ後のデータを張り付ける。
   */
    ss.insertSheet('Dupli');
    const ssDupli = ss.getSheetByName('Dupli');

    let spreadsheetId = ss.getId();
    let sheetId = ssDupli.getSheetId();

    // フィルタしたデータを「Dupli」シートにペースト
    let url =
      "https://docs.google.com/spreadsheets/d/" +
      spreadsheetId +
      "/gviz/tq?tqx=out:csv&gid=" +
      sheetId +
      "&access_token=" +
      ScriptApp.getOAuthToken(); // API使用のためのOAuth認証
    let res = UrlFetchApp.fetch(url); // HTTPクライアント用のクラス
    let array = Utilities.parseCsv(res.getContentText()); // CSVテキストを二次元配列で取得
    let lastFilterdCol = array[1].length;
    let lastFilterdRow = array.length;

    // 二次元配列arrayをDupliシートに貼り付け
    ssDupli.getRange(1 ,1 ,lastFilterdRow, lastFilterdCol).setValues(array);

}

補足

isRowHiddenByFilter(rowPosition)メソッドを使用する方法もあるが、スピードの問題から断念。
https://developers.google.com/apps-script/reference/spreadsheet/sheet#isrowhiddenbyfilterrowposition

手順で紹介した方法が早い。
※logtime測定済み。

参考

https://teratail.com/questions/220476
https://gist.github.com/tanaikech/053d3ebbe76fa7c0b5e80ea9d6396011

0
1
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
0
1