[英]How to find and select table from Document in Apps Script?
我正在Google Apps腳本中創建一個函數。 此功能的目的是從文檔中選擇表格並將值移動到創建的電子表格中。 問題是我無法從文檔中獲取表(調試可以,但是日志將所選表顯示為空{}
)。
function addAnswersTable() {
var File = function(Path) { // File object constructor
this.Path = Path;
this.Doc = DocumentApp.openById(this.Path);
this.getTable = new function()
// This function defines
// a getTable method to get
// the first table in the Document
{
if (this.Doc != undefined) {
var range = this.Doc.getBody();
var tables = range.getTables();
var table = tables[0];
return table;
}
}
}
// Creating Excel Table, where first column
// of selected table should be moved
var Table = SpreadsheetApp.create("AnswersTable");
// Creating new File object
var TrueAnswersFile = new File
('1_ne9iBaK-Z36yUYrISr3gru3zw3Qdsneiu14sWnjn34');
// Calling getTable method to get the table placed in File
var TrueAnswersTable = TrueAnswersFile.getTable;
for (var i = 1; i <= TrueAnswersTable.getNumRows; i++) {
// Filling spreadsheet "A" column with cells'
// values from table stored in File
Table.getActiveSheet().getRange("A" + i).setValue(TrueAnswersTable.getCell(1, i).getValue());
};
}
除了電子表格“ A”列中的輸出,我像這樣:
A1。 只是
A2。 細胞'
A3。 列出項目
A4。 表中的值
電子表格實際上是空的
0
的表有4行和1列。
Just, Cells', List item with, Values From Table
。 我可以像上面那樣理解。 如果我的理解是正確的,那么該修改如何?
TrueAnswersFile.getTable
和TrueAnswersTable.getNumRows
。 getValue()
的TrueAnswersTable.getCell(1, i).getValue()
new
的this.getTable = new function()
不是必需的。 getCell(1, i)
的TrueAnswersTable.getCell(1, i)
從第2行的“ B”列檢索值。
getCell(i - 1, 0)
。 但是在此修改中,索引的開頭為0
。 因此,您可以使用getCell(i, 0)
。 setValue()
,過程成本會很高。 在您的情況下,可以使用setValues()
代替它。 當以上幾點反映到您的腳本時,它將變為以下內容。
function addAnswersTable() {
var File = function(Path) {
this.Path = Path;
this.Doc = DocumentApp.openById(this.Path);
this.getTable = function() { // Modified
if (this.Doc != undefined) {
var range = this.Doc.getBody();
var tables = range.getTables();
var table = tables[0];
return table;
}
}
}
var Table = SpreadsheetApp.create("AnswersTable");
var TrueAnswersFile = new File('1_ne9iBaK-Z36yUYrISr3gru3zw3Qdsneiu14sWnjn34');
var TrueAnswersTable = TrueAnswersFile.getTable();
var values = []; // Added
for (var i = 0; i < TrueAnswersTable.getNumRows(); i++) { // Modified
values.push([TrueAnswersTable.getCell(i, 0).getText()]) // Modified
};
Table.getRange("A1:A" + values.length).setValues(values); // Added
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.