繁体   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-2025 STACKOOM.COM