簡體   English   中英

如何使用 Apps 腳本從 Google 表格中的表格末尾獲取 5 行?

[英]How do I get 5 rows from the end of my sheet in Google Sheets using Apps Script?

我的 google 表格文檔中有一張名為“成員”的表格,我想使用 Google Apps 腳本從中獲取 JSON 格式的最后 5 行數據。 我的工作表中只有兩列,所以 JSON 不會很大。

我發現應用程序腳本有一個 getlastrow() function,它返回工作表的最后一行 - 這個 function 對我有幫助嗎? 我是谷歌應用程序腳本的新手,所以我不確定從哪里開始......我該怎么做? 請指導...謝謝!

關於I want to get the last 5 rows' data in JSON format using Google Apps Script. ,如果您預期的 JSON 格式類似於[{"header1": "value1", "header2": "value2"},,,] ,那么下面的示例腳本怎么樣。

示例腳本:

請將以下腳本復制並粘貼到電子表格的腳本編輯器中,包括“成員”表。 並且,請運行此 function。 這樣,您可以看到日志中每一行的最后 5 行以及包含 JSON 數據的數組。

function myFunction() {
  const sheetName = "Members"; // Please set the sheet name.
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const [header, ...values] = sheet.getDataRange().getValues();

  const last5Rows = values.slice(-5); // This is last 5 rows.
  console.log(last5Rows); // You can see this value in the log.

  const obj = last5Rows.map(r => header.reduce((o, h, j) => (o[h] = r[j], o), {})); // This is an array including JSON data of each row.
  console.log(obj); // You can see this value in the log.
}
  • 運行此腳本時,將從“成員”表中檢索值。 並且,檢索最后 5 行,並創建包含每行的 JSON 數據的數組。

筆記:

  • 不幸的是,我不確定我是否能從您的問題中正確理解JSON format 那么,如果上述示例腳本的 output 結果不是您的預期值,您能否提供示例輸入和 output 值? 通過這個,我想修改腳本。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM