2015-04-18 253 views
2

我刚刚在Google Apps中使用DocumentApp,因此寻求一些帮助!使用Google Apps电子表格从Google电子表格添加Google文档

我试图从电子表格中自动创建一个常见问题解答(在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

在代码中你是指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

希望有帮助。

相关问题