首页 文章

使用Apps脚本从Google电子表格添加到Google文档

提问于
浏览
2

我刚开始在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!

}

1 回答

  • 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中检查null值 .

    text类有一个方法将特定偏移值的文本插入特定的String值,如图所示here .

    希望有所帮助 .

相关问题