我刚开始在Google Apps中使用DocumentApp,所以寻求帮助!
我正在尝试从电子表格自动创建常见问题解答(在Google文档中)。如果电子表格行中满足某些条件,我希望脚本在文档中找到问题的类别,并在其下方插入新的问题和响应(推送已经存在的任何内容)。
所以我有一个看起来像这样的文件:
https://docs.google.com/document/d/1fjb3RO6hUY6n7x0bu6WvtcleMWRNC8VQ9U82hXiGqcY/edit?usp=sharing
一个看起来像这样的电子表格:
https://docs.google.com/spreadsheets/d/1fb3ceqP6142_C7QQ1PfkWtVNswOyzOxkWCofvauf4Ps/edit?usp=sharing
这是我正在尝试使用的代码。我遇到了很多错误 - 主要是因为我不太了解所涉及的不同元素是什么。有人能指出我正确的方向吗?
function insertnewquestion() {
//(works fine)Get active document and related spreadsheet
var doc = DocumentApp.getActiveDocument().getBody();
var ss = SpreadsheetApp.openById("xxxxxxx");
var sheet = ss.getSheetByName("xxxxx");
//(works fine)Go through the various rows in the spreadsheet up to the last row
for (var row = 2; row <= sheet.getLastRow(); ++row) {
var status = sheet.getRange(row,4).getValue();
var question = sheet.getRange(row,1).getValue();
var response = sheet.getRange(row,2).getValue();
var category = sheet.getRange(row,3).getValue();
var date = sheet.getRange(row,5).getValue();
//(works fine)find rows with blank status and a response filled in
if (status !== "Entered" && response !== "") {
//(errors! this is where i need help) find the pertinent header
var categoryposition = body.findText(category); //looking for the category header- new text should be added after this, the idea is that what was already under this header will move down
var questionheader = categoryposition.appendText(question); //trying here to add in question text after where the category was found
questionheader.setHeading(DocumentApp.ParagraphHeading.HEADING3); //set question text as heading 3 (so it shows up on table of contents)
questionheader.appendText("\r"+"\r"+response+"\r\r"); //add line breaks and then the response text in normal font, then more line breaks to put space between new stuff and old stuff
//(works fine)Mark in the spreadsheet that it was entered in FAQ and the date so that it isn't double entered next time the script runs
sheet.getRange(row,4).setValue("Entered");
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var date = (month + "/" + day + "/" + year)
sheet.getRange(row,5).setValue(date);
}
else {continue}
}
//(need help!) Refresh table of contents to include new questions
//no idea how to do this!
}
答案 0 :(得分:0)
在您所指的代码body.findText(category);
中,它应该是doc.findText(category);
。也适用于该行:
var categoryposition = body.findText(category);
它返回RangeElement — a search result indicating the position of the search text, or null if there is no match
在添加任何代码行之前,您必须检查categoryposition中的空值。
文本类有一个方法可以将特定偏移值的文本插入特定的字符串值,如图所示here。
希望这有帮助。