Ale*_*tri 2 google-sheets google-apps-script google-forms
我正在研究一个与Google Form的响应表进行交互的脚本。
FormApp.getActiveForm().getDestinationId()
Run Code Online (Sandbox Code Playgroud)
给我电子表格ID,但我找不到获取工作表本身的方法。用户可以更改其名称和位置,因此我需要获取其ID,例如
Sheet.getSheetId()
Run Code Online (Sandbox Code Playgroud)
我还必须确定响应使用的列数。它不等于表格中的问题数量。我可以计算表格中的项目数:
Form.getItems().length
Run Code Online (Sandbox Code Playgroud)
然后搜索gridItems,在每行中添加行数,然后将它们减去一:
+ gridItem.getRows().length - 1
Run Code Online (Sandbox Code Playgroud)
最后,我认为没有办法将每个问题与工作表中的每一列相关联,而是通过某种方式将列名与项目标题进行比较。
谢谢
@tehhowch 非常接近正确答案,但是代码存在问题:不能保证form.getPublishedUrl()并且sheet.getFormUrl()会返回完全相同的字符串。在我的情况下,form.getPublishedUrl()返回一个形成为的 URLhttps://docs.google.com/forms/d/e/{id}/viewform并sheet.getFormUrl()返回https://docs.google.com/forms/d/{id}/viewform. 由于表单 ID 是 URL 的一部分,因此更强大的实现将是:
function get_form_destination_sheet(form) {
const form_id = form.getId();
const destination_id = form.getDestinationId();
if (destination_id) {
const spreadsheet = SpreadsheetApp.openById(destination_id);
const matches = spreadsheet.getSheets().filter(function (sheet) {
const url = sheet.getFormUrl();
return url && url.indexOf(form_id) > -1;
});
return matches.length > 0 ? matches[0] : null;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
现在,有一种方法可以通过使用来验证Google表格文件中具有多个链接表格的哪个表格与当前表格相对应-该表格Sheet#getFormUrl()已于2017年添加到Sheet该类中。
function getFormResponseSheet_(wkbkId, formUrl) {
const matches = SpreadsheetApp.openById(wkbkId).getSheets().filter(
function (sheet) {
return sheet.getFormUrl() === formUrl;
});
return matches[0]; // a `Sheet` or `undefined`
}
function foo() {
const form = FormApp.getActiveForm();
const destSheet = getFormResponseSheet_(form.getDestinationId(), form.getPublishedUrl());
if (!destSheet)
throw new Error("No sheets in destination with form url '" + form.getPublishedUrl() + "'");
// do stuff with the linked response destination sheet.
}
Run Code Online (Sandbox Code Playgroud)
如果您已取消链接表单和目标电子表格,那么显然您将无法使用getDestinationId或getFormUrl。
| 归档时间: |
|
| 查看次数: |
4910 次 |
| 最近记录: |